Off-topic, but too long for a comment.
Your scanf
line is actually wrong (not referring to the whitespace), and you're just getting lucky that it works here. You need to remove the ampersand &
in front of text
. What you have passes the address of text
to scanf
, which is actually a pointer to a char[10]
. For scanf(" %s", text);
, text
"decays" to a pointer to its first element (char*
) which what you actually want. Here, it just so happens that the address of the array (&text
) is the same as the address to the first element in the array (&(text[0])
, or *(text + 0)
), since they're both in automatic storage at the same place. If, for example, you had something like
char* text = malloc(10);
scanf(" %s", &text);
you would invoke undefined behavior by overwriting memory starting at the address of the pointer to your malloc
ed memory. Here, the address of text is an address to the pointer in automatic storage, whereas the memory it actually points to is somewhere else. You can see this illustrated in the following program.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char text[10];
char* text2 = malloc(10);
printf("address of text = %p\n", (void*)(&text)); // same address as below
printf("address of text[0] = %p\n", (void*)(&(text[0]))); // same address as above
printf("address of text2 = %p\n", (void*)&text2); // different than below
printf("address of text2[0] = %p\n", (void*)(&(text2[0]))); // different than above
return 0;
}
&text == &(text[0])
, showing the address of the array and the address of the first element of the array are equivalent, however &text2 != &(text2[0])
, showing the address of the pointer is not equal to the address of the first element of the memory you've malloc
ed.
Illustrated here:
https://godbolt.org/z/N2TKvK