如何从指针变量计算数组的大小?

har*_*rsh 2 c arrays pointers

我有数组的指针(数组在内存中).我可以从指针计算数组的大小吗?我实际上不知道数组在内存中的位置.我只得到指针地址(假设9001)使用该地址我必须计算数组大小.

谢谢.

Die*_*Epp 11

不,您无法计算数组的大小.C中的对象不携带类型信息,因此您必须提前安排知道数组的大小.像这样的东西:

void my_function(int array[], int size);
Run Code Online (Sandbox Code Playgroud)


pax*_*blo 5

你不能在C中做到这一点.指针的大小是指针的大小,而不是它可能指向的任何数组的大小.

如果您最终得到一个指向数组的指针(显式地使用类似的东西char *pch = "hello";或隐式使用数组衰减,例如将数组传递给函数),则需要单独保存大小信息,例如:

int twisty[] = [3,1,3,1,5,9];
doSomethingWith (twisty, sizeof(twisty)/sizeof(*twisty));
:
void doSomethingWith (int *passages, size_t sz) { ... }
Run Code Online (Sandbox Code Playgroud)

以下代码说明了这一点:

#include <stdio.h>

static void fn (char plugh[], size_t sz) {
    printf ("sizeof(plugh) = %d, sz = %d\n", sizeof(plugh), sz);
}

int main (void) {
    char xyzzy[] = "Pax is a serious bloke!";
    printf ("sizeof(xyzzy) = %d\n", sizeof(xyzzy));
    fn (xyzzy, sizeof(xyzzy)/sizeof(*xyzzy));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我系统的输出是:

sizeof(xyzzy) = 24
sizeof(plugh) = 4, sz = 24
Run Code Online (Sandbox Code Playgroud)

因为24字节数组在函数调用中衰减为4字节指针.