Just a quick question.
I can write
char string[] = "Hello world";
char *p = string;
printf("%s", p);
And have it print Hello world as output. But how is the pointer working here?
Each point in an array has a separate memory location, right? So the string array being 12 long, would take up 12 memory spaces. I thought a pointer could only point to one memory location, not 12. How is the pointer p achieving this?
With normal arrays and pointers if you want to scale the array you do *p++, as you’re going through each memory location and printing its value. Why is that you have to traverse the array 1 by 1 there, but here it simply points to the whole thing?
It just seems to me like with one (int arrays) you’re incrementing the pointers as each pointer can only point to one memory location, but with char arrays it can point to all of them somehow.
You’re right, a pointer can only point to one memory location. When dealing with arrays, the pointer points at the location of the first element. When you use
printf, it basically takes the pointer (pointing to the first element of the string), and prints until reaching the null terminating character,\0.Here is a good explanation of pointers vs arrays in c:
http://www.cs.bu.edu/teaching/cpp/string/array-vs-ptr/