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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.