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

时间:2015-07-02 08:38:33

标签: c arrays pointers char

拥有以下代码:

char data[2048];

一个声明如下的函数:

int f(char** data);

我可以安全地这样称呼它:

f((char**)&data);

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

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

4 个答案:

答案 0 :(得分:7)

不,你不能。

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).
但是,当然,你实际需要的将取决于你的用例。

答案 1 :(得分:3)

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

函数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

答案 2 :(得分:1)

this more detailed example中所述:

  

虽然数组名称可能会衰减为指针,但数组的地址不会衰减为指向指针的指针。为什么要这样呢?这样处理数组有什么意义呢?

     

指针的指针有时会被传递以修改指针(简单的指针参数在这里不起作用,因为C通过值传递,这只会允许修改指向的内容,而不是指针本身)。这是一些虚构的代码(不会编译):

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;
}

答案 3 :(得分:0)

你可以这样做。

element.onselectstart = function() { return false; };

element.ondragstart = function() { return false; };

element.ontouchstart = function(e) { e.preventDefault(); };