我可以安全地将 &char[] 转换为 char** 吗?

Can I safely cast a &char[] to char**?

具有以下代码:

char data[2048];

还有一个这样声明的函数:

int f(char** data);

我可以这样称呼它吗:

f((char**)&data);

如果我只使用 &data,编译器会发出以下警告:

warning C4047: 'function' : 'char **' differs in levels of indirection from 'char (*)[2048]'

指向指针的指针不是数组,也不是指向数组的指针,也不应该用来指向数组。除了可以用来指向指针数组的第一项的特殊情况,这里不是这种情况。

函数 int f(char** data); 不能接受 char data[2048]; 数组作为参数。要么改变数组类型,要么重写函数

正确的替代函数是:

int f (char* data);
int f (char data[2048]); // completely equivalent to char* data
int f (char (*data)[2048]); // array pointer, would require to pass the address of the array

不,你不能。

data 是一个数组。 &data 是一个 指向数组 的指针。它不是指向指针的指针。尽管 data 衰减 指向多个上下文中的指针,但它本身并不是一个指针 - 取地址可以得到数组的地址。

如果你想要一个指向数组指针的指针,你可以尝试这样的事情:

char *pdata = data; // data decays to a pointer here
                    // (a pointer to the first element of the array)
f(&pdata);          // Now &pdata is of type char ** (pointer to a pointer).

不过,当然,您实际需要的将取决于您的用例。

this more detailed example所述:

While an array name may decay into a pointer, the address of the array does not decay into a pointer to a pointer. And why should it? What sense does it make to treat an array so?

Pointers to pointers are sometimes passed to modify the pointers (simple pointer arguments don't work here because C passes by value, which would only allow to modify what's pointed, not the pointer itself). Here's some imaginary code (won't compile):

void test(int** p)
{
    *p = malloc ... /* retarget '*p' */
}


int main()
{
    int arr[] = {30, 450, 14, 5};
    int* ptr;

    /* Fine!
    ** test will retarget ptr, and its new value
    ** will appear after this call.
    */
    test(&ptr);

    /* Makes no sense!
    ** You cannot retarget 'arr', since it's a
    ** constant label created by the compiler.
    */
    test(&arr);

    return 0;
}

你可以这样做。

char data[2048];
char *a=&data[0];
char **b=&a;
f(b);