Log in from a computer to take this course

You'll need to log in from a computer to start Learn C. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

In the lesson on arrays, you learned that an array is a contiguous block of memory reserved for many variables of the same type. Because of this structured organization, a pointer is well suited to work with this data type. If we have an integer array, we can use pointers and pointer arithmetic to iterate through the array to access or manipulate its values. This might seem like an overcomplicated way to work with arrays, but there are some advanced applications in which working with an array through a pointer is necessary.

Consider an array of integers arr. Since arrays are contiguous blocks of memory, if we have a pointer to the first element, we can use pointer arithmetic to access the rest of the array. Keep in mind that while this is a valid way to work with arrays, it is unsafe. Accessing memory outside of the bounds of the array will not cause a program crash, but will silently corrupt data stored in those addresses. In the case of a read operation, it will return a random value.

With caution in mind, let’s see how we can carefully access and manipulate elements in an array using pointers. The following code prints all of the elements of an array:

int arr[10] = {2, 4, 7, 1, 10, 3, 11, 6, 20, 5}; int* ptr = &arr[0]; // Pointer to the first element for(int i = 0; i < 10; i++){ printf("%i\n", *ptr); // Dereference the pointer and print the value ptr++; // Increment the pointer to point to the next int in the array }

The following code illustrates how to change the values of an array using pointers by changing all the elements in an array to three:

int arr[10] = {2, 4, 7, 1, 10, 3, 11, 6, 20, 5}; int* ptr = &arr[0]; // Pointer to the first element for(int i = 0; i < 10; i++){ *ptr = 3; // Dereference the pointer and assign the value at the ptr address to three ptr++; // Increment the pointer to point to the next int in the array } for(int i = 0; i < 10; i++){ printf("%i",arr[i]); }

The output of the code above will be a string of 10 threes. These techniques are also applicable to strings since they are arrays too. It cannot be stressed enough: be very careful when working with pointers!

Instructions

1.

Create a pointer to an int called ptr and have it point to the last element in array arr.

2.

Using pointer arithmetic, loop through arr and print the contents in reverse.

3.

Create a pointer to a char called ptr2 and set it to point to the first character in string s.

4.

Using pointer arithmetic on ptr2, loop through the string s and replace all the characters with the character ‘#‘.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?