I was searching about this code that I didn't believe that works, but I found something in books about table of strings that exists in compiler.
char *p;
p = "something";
printf("%s", p);
How this code works ?
I was searching about this code that I didn't believe that works, but I found something in books about table of strings that exists in compiler.
char *p;
p = "something";
printf("%s", p);
How this code works ?
"something"
is a string literal, which is a null-terminated character array that is stored in read-only memory. p
is a pointer to char. Since you set this pointer to point at read-only memory, you should always declare it as const char*
.
sizeof(p)
gives the size of p. p
is a pointer so you get the size of a pointer, 4 bytes on your specific system.
Had you instead declared an array char arr[] = "something";
you would have gotten a copy of something stored in your local array, where you can also modify it. And if you take sizeof an array, you get the expected size. In the array case sizeof(arr)
would give you 9+1=10 bytes.
For reference, please read:
char *p = "something";
This is read only so you are able to print it.
sizeof(p);
You are printing the sizeof pointer not the size of the string.