-
C Strings and * Operator
How come you do not have to use the dereference operator when printing the string my_string in the following code?
Code:
char *my_string = malloc(sizeof(*my_string)*100);
printf("Enter a string.\n");
scanf("%s", my_string);
printf("%s", my_string);
I am learning C and do not quite understand this. I appreciate the help.
-
Because the printf modifier %s expects a char*, not a plain char. And my_string in your example is a char*.
-
-
The reason it expects char* is because char can only hold one character. So, in C, a string is a pointer to where the first character in an array resides. It then "travels" the memory, reading one byte after another until it reaches a '\0' character. That is why it requires a char*.
-
Good explanation. Thanks for the help guys.
-
yep, same reason why scanf("%s", my_string); doesn't require a reference operator (&) when you pass a string to it, because array identifiers are really pointers.
-
It's called the address of operator.
References doesn't exist in C.