Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sizeof(msg) shorter than the string?

Tags:

c

pointers

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?

like image 993
Maisha Avatar asked Oct 26 '25 06:10

Maisha


1 Answers

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.

like image 56
Sourav Ghosh Avatar answered Oct 28 '25 21:10

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!