Reputation: 1
there is a question puzzles me.In the code below msg and quote are both char array.why sizeof(msg) and sizeof(quote) gave me different result?
Code:
#include <stdio.h>
void fortune_cookie(char msg[])
{
printf("Message reads: %s\n",msg);
printf("msg occupies %i bytes\n",sizeof(msg));
}
int main()
{
char quote[] = "Cookies make you fat";
printf("quote occupies %i bytes\n",sizeof(quote));
fortune_cookie(quote);
return 0;
}
Result:
quote occupies 21 bytes
Message reads: Cookies make you fat
msg occupies 8 bytes
Upvotes: 0
Views: 136
Reputation: 65
Hiiii..
When sizeof() is applied to the name of an array the result will be the size of the whole array in bytes. Here the name of an array is converted to a pointer to the first element of the array.
Now when we pass this array as a Parameter to the function the receiving function variable is just the pointer , which will point the same array, we can not pass an array as Call by Value.
So "sizeof(msg)" will always display Size of a pointer.
For refrence see .:http://en.wikipedia.org/wiki/Sizeof and Stack
Upvotes: 0
Reputation: 51
sizeof
an array equals total of sizeof
each element.
When you pass an array to a function, it passes the pointer.
In your case:
quote
occupies 21 bytes: Means your char array has 21 elements and each element size is 1.
msg
occupies 8 bytes: Means your parameter is a pointer, it will hold 8 bytes on 64-bit machine and 4 bytes on 32-bit machine.
Upvotes: 1
Reputation: 98108
The quote
is an array in the scope of the main
function. The sizeof an array is the number of bytes that it occupies, which is the length of your string + 1 for the null byte at the end.
When you pass it to the fortune_cookie
, it is demoted to a pointer. The size of a pointer is 4 bytes in 32bit architectures and 8 bytes in 64bit architectures. To see the same output, you can change the signature of the fortune_cookie
:
void fortune_cookie(char msg[21])
But that is generally not practical.
Upvotes: 0
Reputation: 4002
Here char quote[] = "Cookies make you fat";
memory is allocated for the message inside quote[]
that's why the size of the quote[]
is 21 bytes.
void fortune_cookie(char msg[])
Here char msg[]
is same as char *msg
and its a pointer to the quote
, because you are passing quote to fortune_cookie(quote);
Size of pointer is depending on the machine. I think you are using 64 bit machine that's why you are getting 8 as its size.
Upvotes: 0