Jinglei.Y Jinglei.Y - 3 months ago 8
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
str
be a string and a pointer at the same time?
I know that a string is a pointer to
char
. So I think
str
is just a
pointer
.

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

Is it how the compiler work?

P.S

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

M.M M.M
Answer

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).