I am quite confused about the concepts of the string literal and its pointer in C
.
For example, if I want to define a pointer to a character, and :
char* s = "hello";
printf("%s\n",s); // this print "hello"
Because in C, strings are arrays of characters. So in my opinion, char* = "hello"
should define a character pointer that points to the first element in the string (i.e. the memory address for 'h'). How it generates the whole string literal when printed?
Another example is when a char pointer is defined as:
void stringFunc(char strings[ROWS][COLS])
{
char* initial_p = strings;
}
It should be fine, because strings
is a pointer and we can make a name (initial_p) of that pointer. However, gcc sticks that it's wrong and forces the correction to:
char* initial_p = *strings;
I can't figure out the reason. because *strings
should be a dereference of the pointer, and should not be assigned to a pointer's name.
CodePudding user response:
Because in C, strings are arrays of characters. So in my opinion,
char* = "hello"
should define a character pointer that points to the first element in the string (i.e. the memory address for 'h'). How it generates the whole string literal when printed?
It generates the entire string literal when printed because the %s
format specifier for printf
outputs a string given a pointer to its first character. It could also have been defined to dereference and output the first character or to print out the pointer in hex, but it wasn't defined that way because this behavior is more useful. It's useful to have an easy way to output a string, and the logical way to specify that string is by a pointer to its first character because that's the C way of doing it.
I can't figure out the reason. because *strings should be a dereference of the pointer, and should not be assigned to a pointer's name.
In this case, strings
is a double array type. It's just not a char *
and so can't be assigned to a variable of that type.
CodePudding user response:
How it generates the whole string literal when printed?
From C11:
s
If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type. Characters from the array are written up to (but not including) the terminating null character. If the precision is specified, no more than that many bytes are written.
So, printf
looks for a null-byte when no length modifier is specified as a signal to stop. Otherwise, it continues printing until it sees a null-byte in memory or the system realizes it's accessing memory out of bounds — in which case you will most likely get a segmentation violation signal, but nearly anything can happen as the behaviour is undefined.