Hi, I'm having trouble understanding pointers and arrays.

course[] = "Numerical Methods";
printf("%c %s\n", course[6], course);
printf("%c %s\n", course[6], &course[0]);

I don't understand how the second print statement prints the same thing as the first. How does &course[0] print out the entire array? I thought it was just getting the address of the first element of the array.

In C, the name of the array, is ALMOST the same thing, as a constant pointer - and it points to the first element of the array - array[0].

So

char a[] = "Hello there.";

now the address of a, is the address of a[0], and a string operation includes all the char's until the end of string char is reached: '\0' or 0.

After the last e in a[] above, there would be an end of string char to mark it, even though you can't see it when the string is printed.

Edited 5 Years Ago by Adak: n/a

I thought it was just getting the address of the first element of the array.

That's exactly what it's doing. However, that address is being interpreted by scanf() as the starting address of a string. To print the address itself, use %p and cast to void* :

printf("%c %p %s\n", course[6], (void*)course, course);
printf("%c %p %s\n", course[6], (void*)&course[0], &course[0]);

Also note that in value context (ie. just about everywhere) course and &course[0] evaluate to the same thing.

This question has already been answered. Start a new discussion instead.