【问题标题】:Typecasting a double pointer in C [duplicate]在C中键入双指针[重复]
【发布时间】:2015-01-13 08:57:12
【问题描述】:

在参数传递过程中我无法弄清楚这个错误。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef char my_char;

void myfunc(const my_char** data)
{
    printf ("%s\n", *data);
    printf ("%s\n", *(data + 1));
}

int main(){

    char **mydata;
    mydata = malloc(sizeof(char*)*2);
    mydata[0] = malloc(sizeof(char)*50);
    mydata[1] = malloc(sizeof(char)*50);

    memset(mydata[0],'\0',50);
    memset(mydata[1],'\0',50);
    strcpy (mydata[0], "Hello");
    strcpy (mydata[1], "world");

    myfunc((my_char**)mydata);

    free (mydata[0]);
    free (mydata[1]);
    free (mydata);

    return 0;
}

它工作正常。但是当我明确输入参数时会发出警告。为什么会这样? 显示的警告是:

warning: passing argument 1 of ‘myfunc’ from incompatible pointer type

据我所知,类型转换应该有助于编译器理解指针所持有的数据类型。但在这里它根本没有帮助。

【问题讨论】:

  • const my_char**my_char** 不兼容,你看。
  • 这是一个合理的问题,不确定是否有否决票。它在C FAQ 中,但其他介绍性材料可能未涵盖该主题。
  • @SouravGhosh 我认为 const 没有太大区别。
  • 你的直觉是对的,但编译器对待它们的方式不同
  • @darknight 不,直觉是错误的,编译器是对的。编译器几乎总是正确的。当它不正确时,一组训练有素的猴子通常会修复它。但你的直觉是只有你才能解决的。

标签: c casting double-pointer


【解决方案1】:

在对数据类型进行类型转换时使用const

myfunc((const my_char**)mydata);

您在函数中以 const 的形式获取该值。

【讨论】:

  • 您能否详细说明为什么会出现这种情况? const int* x = (int*) 1; 不会产生警告,但只需添加另一个间接级别即可。
【解决方案2】:

删除const,添加一个 const 会导致传递的参数类型与声明混淆,并像这样对数据元素进行类型转换:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef char my_char;

void myfunc(my_char** data)
{
    printf("%s\n", *data);
    printf("%s\n", *(data + 1));
}

int main(){

    char **mydata;
    mydata = (char **)malloc(sizeof(char*)* 2);
    mydata[0] = (char *)malloc(sizeof(char)* 50);
    mydata[1] = (char *)malloc(sizeof(char)* 50);

    memset(mydata[0], '\0', 50);
    memset(mydata[1], '\0', 50);
    strcpy(mydata[0], "Hello");
    strcpy(mydata[1], "world");

    myfunc((my_char**)mydata);

    free(mydata[0]);
    free(mydata[1]);
    free(mydata);

    return 0;
}

【讨论】:

  • 我没有投反对票,但原因应该是。您正在更改不正确的函数参数类型
  • 感谢 gopi,我会将其添加到答案中。
  • 最好not cast malloc。对于不修改其指向数据以通过使用const 来指示这一点的函数来说,这是一个很好的代码设计,因此建议删除它不是一个好建议。 (虽然诚然没有“好的”解决方法)
【解决方案3】:

您可以从 void myfunc(const my_char** data) 中删除 const,即 void myfunc(my_char** data) 或者当类型转换提供 const 即 myfunc((const my_char**)mydata);

【讨论】:

    猜你喜欢
    • 2021-01-13
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 2021-07-31
    相关资源
    最近更新 更多