c - 从不兼容的指针类型返回(const vs non-const)。 C/海湾合作委员会

标签 c gcc

我有以下代码:

typedef uint8_t array_t[8];
static array_t _my_array;
static const array_t * foo(void) {
    return &_my_array; // <-- return from incompatible pointer type
}   

如何解决这个错误?我做错了什么?
我必须将 _my_array 转换为 (const array_t *) 吗?从指针转换为 const 指针不应该是隐式的吗?

注意:

return _my_array;

工作一样,即编译时出现相同的警告。

最佳答案

问题是 const ;该函数返回 const array_t * (指向 const array_t 的指针),但返回的表达式,&_my_array , 类型为 array_t * , 并且这两种类型不兼容。

最简单的修复是删除 const从返回类型:

typedef uint8_t array_t[8];
static array_t _my_array;
static array_t * foo(void) {
    return &_my_array;
}

编辑:

我对提出编译器错误犹豫不决,但我想出了一个测试程序,我认为它表明 gcc 中的错误或 C 标准的一个非常模糊的方面。

typedef int this_type;
typedef int that_type[8];

static this_type this;
static that_type that;

static const this_type *this_func(void) {
    return &this;
}

static const that_type *that_func(void) {
    return &that;
}

当我用 gcc -c -std=c99 -pedantic-errors c.c 编译它时(gcc 4.5.2),我得到:

c.c: In function ‘that_func’:
c.c:12:5: error: return from incompatible pointer type

为什么它会提示来自 that_type* 的隐式转换至 const that_type* , 但与 this_type* 的转换无关至 const this_type* .

that_type是一个typedef,它是数组类型的别名,that_type*是指向数组的指针(不是指向数组元素的指针);据我所知,没有数组到指针的转换。我不认为 this_type是整数类型,that_type是数组类型应该有所不同。

另一个数据点:在 Solaris 9 上,cc -c -Xc c.c不提示。

从逻辑上讲,将指向 foo 的指针转换为指向 const foo 的指针应该是安全的;它不会产生任何违反常量正确性的机会。

如果我是对的,那么问题中的代码是有效的,gcc 的警告是不正确的,您可以通过删除 const 来解决它。在函数定义上(让它返回 array_t* 而不是 const array_t* ,或者通过在 return 语句上添加强制转换:

return (const array_t*)&_my_array;

如果我错了,我希望很快有人会指出。

(我故意使用 this 作为标识符,这是一个 C++ 关键字。这是一个 C 问题。我知道 C++ 在这方面的规则略有不同。)

编辑 2: 我刚刚提交了一份 gcc bug report .

编辑 3: Joseph S. Myers 回复了我的错误报告:

This is not a bug. You can implicitly convert "pointer to int" to "pointer to const int", but not "pointer to array of int" to "pointer to array of const int" (see 6.5.16.1), and "const that_type *" is "pointer to array of const int" (there is no such type as "pointer to const array of int", which would be a permitted target of such a conversion; see 6.7.3#8).

关于c - 从不兼容的指针类型返回(const vs non-const)。 C/海湾合作委员会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7691295/

相关文章:

c - 初始化指针时,字符串文字与 char 数组

c - 在 popen 工作时缓冲

c - 从 void 函数返回

c - 静态编译链接 Openssl

c - 为什么gdb8.2在Centos7 aliyun上编译出错?

c++ - GCC如何处理变量重定义

c - 为什么我的 UDP 客户端发送数据比服务器接收数据花费的时间更长?

c - While循环变量初始化和变量类型(C)

gcc - 无法识别文件格式;使用 GCC 将其视为链接描述文件

c++ - SIGABRT 在 Mac OS X 上使用 GCC 抛出和捕获异常