在 C 模块(也称为编译单元)中,我想要一些私有(private)数据,但将其只读 公开给外界。我通过在我的 .c
文件中声明的 struct
中的字段和在我的 .h
文件中声明的返回 < em>指向 const 的指针 指向该字段。例如,对于 string,这可能类似于以下内容:
// header:
typdef struct foo foo;
const char *foostr(const foo *f);
// implementation:
struct foo
{
char *str;
};
const char *foostr(const foo *f)
{
return foo->str;
}
现在我的问题是,我有一个本身就是数组的对象数组。所以在我的 struct
中,我有一个指向数组的指针,并且我尝试从我的函数返回一个指向相应 const
数组的指针。考虑以下示例代码:
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t shape[64];
typedef struct foo
{
shape *shapes;
} foo;
foo *createfoo(void)
{
foo *f = malloc(sizeof *f);
if (!f) return 0;
// 10 empty shapes:
f->shapes = calloc(10, sizeof *(f->shapes));
if (!f->shapes)
{
free(f);
return 0;
}
return f;
}
const shape *fooshapes(const foo *f)
{
return f->shapes;
}
用 gcc -c -std=c11 -Wall -Wextra -pedantic
编译它,我收到以下警告:
constarr.c: In function ‘fooshapes’:
constarr.c:31:13: warning: pointers to arrays with different qualifiers are incompatible in ISO C [-Wpedantic]
return f->shapes;
~^~~~~~~~
我理解双指针与指向常量的双指针不兼容,这也是原因,但我不认为这是相关的,是吗?那么,为什么不允许将指向数组的指针隐式转换为指向 const
数组的指针呢?我应该怎么做?
我现在所做的是添加一个像这样的显式转换:
const shape *fooshapes(const foo *f)
{
return (const shape *) f->shapes;
}
这当然会使编译器静音,我几乎可以肯定它在实践中总是能正常工作。 “const hole”在这种情况下不存在,因为对于数组,没有非常量内部指针。但这仍然留给我两个进一步的问题:
- 我的假设是否正确,这不会导致
const
正确性出现漏洞? - 此处的显式转换是否违反标准?
最佳答案
这确实是您在问题中提到的同一个双指针问题。
您可以将指向 T 的指针转换为指向常量 T 的指针。但应用于数组的 const
限定元素类型,而不是数组类型 (C11 6.7.3.9),因此这不是您要在此处尝试执行的操作。您不是在尝试将 T 的指针转换为 T 的常量数组指针,而是尝试转换为 const-T 的指针和这两种类型在 C 中不兼容。
关于c - 指向数组的指针与指向 'const' 数组的指针不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50164803/