char pointer as function parameter

牧云@^-^@ 提交于 2019-12-11 06:35:46

问题


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, so sizeof 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 of sizeof operator.

  • In A() function, p is a pointer, so sizeof 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!