I have just started to learn how to program and I am using this book called Head First C. There are sections in the book called Brain Power. In one of these sections it was written.
void fortune_cookie(char msg[])
{
printf("Message reads: %s\n", msg);
printf("msg occupies %i bytes\n", sizeof(msg));
}
The output:
Cookies make you fat
msg occupies 8 bytes
The Brain Power question was: Why do you think sizeof(msg) is shorter than the length of the whole string? What is msg? Why would it return different sizes on different machines?
In this particular case
char msg[]
is same as
char * msg
so what you're really seeing is the output of sizeof(char *).
As the size of a pointer is dependent on the architecture/compiler, you'll see different output in different machine.
Also, please note, as the sizeof operator produces a result of type size_t, you should be using %zu format specifier to print the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With