Different sizeof results

坚强是说给别人听的谎言 提交于 2019-11-27 14:41:11

Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brackets are syntactic sugar. There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want.

// These all do the same thing
void foo(char cvalue[8])
void foo(char cvalue[])
void foo(char *cvalue)

C and C++ arrays are not first class objects; you cannot pass arrays to functions, they always decay to pointers.

You can, however, pass pointers and references to arrays. This prevents the array bounds from decaying. So this is legal:

template<typename T, size_t N>
void foo(const T(&arr)[N])
{
    int n = sizeof(arr);
}
dagorym

In the first example, cvalue as passed parameter is in really just a pointer to a character array and when you take the sizeof() of it, you get the size of the pointer. In the second case, where you've declared it as a local variable, you get the size of the the entire array.

The size of the parameter on 32-bit systems will be 4 and on 64-bit systems compiled with -m64 will be 8. This is because arrays are passed as pointers in functions. The pointer is merely a memory address.

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