Jinglei.Y Jinglei.Y - 5 months ago 13
C Question

How to understand string variables? Are they strings and pointers simultaneously?

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[]) {
char str[] = "hello";
printf("%s, %p", str, str);
return 0;

The code above gives the output

hello, 0x7fff5fbff7aa

What confuses me is that why can
be a string and a pointer at the same time?
I know that a string is a pointer to
. So I think
is just a

But how does the compiler know that
gives the string that
points to?

Is it how the compiler work?


I suppose the same thing happens to the situation that when we use
to a
variable and we get different output.


In this code str is an array. Arrays and pointers are different. You can make a pointer that points to an element of an array.

In the code printf("%s, %p", str, str); both usages of str actually request a pointer that points to the first element of the array. You could write &str[0] to mean the same thing, but it was a design decision from the start in C that writing the name of an array in most situations would actually request such a pointer.

The printf function is defined so that if it sees %s then it follows (dereferences) the corresponding pointer and prints out characters until it reaches a null terminator. If it sees %p then it prints out some sort of representation of the pointer itself (not what the pointer is pointing to).