Reputation: 29316
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.
Upvotes: 0
Views: 110
Reputation: 4518
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/
Upvotes: 3
Reputation: 121357
You use %s
so it prints till it '\0'
.
Why is that you have to traverse the array 1 by 1 there, but here it simply points to the whole thing?
Here, you use a pointer to a char, and you wanted to print the string. so it's fine. Suppose, if you are using an pointer to an int or other types, this will not quite work. So pointer arithmetic like p++
is used.
Upvotes: 1
Reputation: 14549
The pointer to an array is really a pointer to the first address... And printf will scan from that address on untill it finds the null char... %c and %s differ on that behavior
Upvotes: 1
Reputation: 145829
I thought a pointer could only point to one memory location, not 12. How is the pointer p achieving this?
p
is a pointer to char
and not a pointer to an array. It points to the first element of the string
array.
Now the value of an array is a pointer to its first element so this declaration:
char *p = string;
is actually equivalent to:
char *p = &string[0];
If you increment the pointer:
p++;
p
will point to the next element of the array, that is to string[1]
.
Upvotes: 2