问题
I have a function A that has a char *
parameter. In A()
, I use sizeof
to calculate the size of buf , but I got 8 in i686 machine and 4 in armel machine. why is not it 128? The snippet is as below:
void A(char *p)
{
printf("sizeof p is %d\n", sizeof(p));
}
int main(void)
{
char buf[128];
printf("sizeof buf is %d\n", sizeof(buf));
A(buf);
return 0;
}
the result is like this(in i686):
sizeof buf is 128
sizeof p is 8
Please tell me the reason.
回答1:
Because you print the size of the pointer, and not what it points to. Arrays decays to pointers, and as soon as you pass it to a function you have a pointer instead, and loose all size information of the original array.
回答2:
In
main()
function,buf
is an array, sosizeof buf
gives the size of this array:sizeof(char[128])
(128 bytes). That's because an array is not converted to a pointer when used as operand ofsizeof
operator.In
A()
function,p
is a pointer, sosizeof p
gives the size of this pointer:sizeof(char *)
(8 bytes on your implementation).
回答3:
sizeof(buf)
is 128*sizeof(buf[0])
and sizeof(p) is just sizeof(char*)
.
回答4:
When passed into function, it decays to an ordinary pointer that has size of your native size(4 or 8).
Use strlen() because it checks for a "null" at the end and gives correct size if the array is already initalized.
来源:https://stackoverflow.com/questions/17424078/char-pointer-as-function-parameter