将指向较大数组的指针分配给指向较小 VLA 的指针
Assigning a pointer to a larger array to a pointer to a smaller VLA
我注意到 C 编译器(gcc、clang、tinycc)允许我在没有警告的情况下将指向较大数组的指针分配给指向较小 VLA 的指针:
#include <stdio.h>
#if !__TINYC__
void take_vla(int N, char const X[1][N]) { printf("%zd\n", sizeof(*X)); }
#endif
int main()
{
static char bigarray[]="0123456789abcdefghijklmnopqrstuvwxyz";
//VLA
int n = 3;
char const (*subarray2)[n]=&bigarray;
//char const (*subarray3)[(int){3}]=&bigarray; //VLA but clang doesn't see it as such (a bug, I guess)
#if !__TINYC__
take_vla(3,&bigarray);
take_vla(3,&"abcdefg");
#endif
#if 0
char const (*subarray1)[3]=&bigarray; //-Wincompatible-pointer-types
#endif
}
这是符合 C 的吗?为什么?
const char[3]
与 char[37]
不兼容。
"pointer to qualified type" 也不与 "pointer to type" 兼容 - 不要将其与 "qualified pointer to type" 混淆。 (遗憾的是,Const 正确性不适用于数组指针。)
相关部分为简单赋值规则C17 6.5.16.1:
- the left operand has atomic, qualified, or unqualified pointer type, and (considering
the type the left operand would have after lvalue conversion) both operands are
pointers to qualified or unqualified versions of compatible types, and the type pointed
to by the left has all the qualifiers of the type pointed to by the right;
查看各种编译器:
"gnu mode" 中的 gcc 对于检查 C 一致性没有用。您必须使用 -std=cxx -pedantic-errors
进行编译。之后 gcc 表现良好:gcc -std=c17 -pedantic-errors
:
error: pointers to arrays with different qualifiers are incompatible in ISO C [-Wpedantic]
icc 提供与 gcc 相同的诊断,它工作正常。
而clang -std=c17 -pedantic-errors
不报错,显然不符合C标准。
我注意到 C 编译器(gcc、clang、tinycc)允许我在没有警告的情况下将指向较大数组的指针分配给指向较小 VLA 的指针:
#include <stdio.h>
#if !__TINYC__
void take_vla(int N, char const X[1][N]) { printf("%zd\n", sizeof(*X)); }
#endif
int main()
{
static char bigarray[]="0123456789abcdefghijklmnopqrstuvwxyz";
//VLA
int n = 3;
char const (*subarray2)[n]=&bigarray;
//char const (*subarray3)[(int){3}]=&bigarray; //VLA but clang doesn't see it as such (a bug, I guess)
#if !__TINYC__
take_vla(3,&bigarray);
take_vla(3,&"abcdefg");
#endif
#if 0
char const (*subarray1)[3]=&bigarray; //-Wincompatible-pointer-types
#endif
}
这是符合 C 的吗?为什么?
const char[3]
与 char[37]
不兼容。
"pointer to qualified type" 也不与 "pointer to type" 兼容 - 不要将其与 "qualified pointer to type" 混淆。 (遗憾的是,Const 正确性不适用于数组指针。)
相关部分为简单赋值规则C17 6.5.16.1:
- the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
查看各种编译器:
"gnu mode" 中的 gcc 对于检查 C 一致性没有用。您必须使用
-std=cxx -pedantic-errors
进行编译。之后 gcc 表现良好:gcc -std=c17 -pedantic-errors
:error: pointers to arrays with different qualifiers are incompatible in ISO C [-Wpedantic]
icc 提供与 gcc 相同的诊断,它工作正常。
而
clang -std=c17 -pedantic-errors
不报错,显然不符合C标准。