Wednesday, 1 November 2017

C Programming - Arrays, addresses and pointers

#include <stdio.h>

int main(int argc, char **argv) {
char str1[] = "Hello";
char *str2 = "Goodbye";
// str2 = &str1;
// str2 = str1;
printf("%d %d %s\n", &str1, str1, str1);
printf("%d %d %s\n", &str2, str2, str2);
return 0;
}

Let’s now look at how pointers and addresses work in C – and why arrays are special. In the code shown above I declare two string variables, str1 and str2. You can create string variables using either syntax but you need to understand that these two variables are by no means the same as one another. The first, str1, declared with a pair of square brackets is an array. The second, str2, declared using the star operator, *, is a pointer. As we know (see previous article), an array and an address are equivalent. So str1 is the address at which the array of characters in the string “Hello” are stored. But str2 is a pointer whose value is not the string “Goodbye” but the address of that string. So str2 'points to' the address at which the characters “Goodbye” are stored.

This should be clearer when you run the code.

When displayed as an integer value, the address of str1 (returned by the & address-of operator) is the same as the value of the variable str1 itself. That’s because str1 is an array - and an array is, in effect, an address.

But the address of str2 (returned by the & address-of operator) is different from the value of the str2 variable. Here the address gives us the location in memory of the pointer variable, str2. But the value of that variable is the address of the array of chars to which it points.

str1 is the location of the start of this array of characters, “Hello”, in computer memory. The address of str1 is the location where that string of chars begins.

But the value of the pointer variable str2 is a number that gives the location of the start of the array of characters “Goodbye” in computer memory. The address of str2 is the location where the str2 pointer variable is stored – and if we just want to get at data in the array, the address of the pointer variable itself is of no interest to us. For now, I’m only interested in the address of the array to which this pointer points. The value of str2 is the address of that array: the address of the first character in the string “Goodbye”.

The video below is taken from my online course, Advanced C Programming: Pointers. You can subscribe to this course, for a limited period, and save 63% by clicking this link. This lets you join up for $35 (regular price is $95): https://www.udemy.com/advanced-c-programming-pointers/?couponCode=CPOINTERS2017