下面两段代码在c++文件中运行正常,但在c中编译错误,为什么? 它似乎使用 const 变量在 c 中导致一些问题, 我使用 dev c++ 5.11
19 3 C:\Users\tjc\Desktop\c練習\Untitled4.c [Error] variable-sized object may not be initialized
19 3 C:\Users\tjc\Desktop\c練習\Untitled4.c [Warning] excess elements in array initializer
19 3 C:\Users\tjc\Desktop\c練習\Untitled4.c [Warning] (near initialization for 'A')
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
int cmpW( const void* p1, const void*p2){
float *pf1 = (float*)p1;
float *pf2 = (float*)p2;
return pf1[0] - pf2[0];
}
int cmpH( const void* p1, const void*p2){
float *pf1 = (float*)p1;
float *pf2 = (float*)p2;
return pf2[1] - pf1[1];
}
int main(void)
{
const size_t n = 5;
float A[n][2] = {0}; //line 19
int i=0;
for(i=0; i<n; ++i){ // Data input.
printf("W H: ");
scanf("%f %f", &A[i][0], &A[i][1]);
}
qsort(A, n, sizeof(float) * 2, cmpW ); // By weight
for(i=0; i<n; ++i) // Data input.
printf("(%f, %f) ", A[i][0], A[i][1]);
printf("\n");
qsort(A, n, sizeof(float) * 2, cmpH ); // By height
for(i=0; i<n; ++i) // Data input.
printf("(%f, %f) ", A[i][0], A[i][1]);
printf("\n");
system("pause");
}
最佳答案
这是 C 和 C++ 如何对待限定为 const
的变量的差异。在 C 中,const
变量不被视为真正的常量,因此声明 float A[n][2]
被视为可变长度数组,即使 n
被声明为 const int
。
摘自 C standard 的第 6.6 节(常量表达式) :
8 An arithmetic constant expression shall have arithmetic type and shall only have operands that are integer constants, floating constants, enumeration constants, character constants,
sizeof
expressions whose results are integer constants, and_Alignof
expressions. Cast operators in an arithmetic constant expression shall only convert arithmetic types to arithmetic types, except as part of an operand to asizeof
or_Alignof
operator.
因为A
被认为是一个可变长度数组,所以它可能不会被初始化。
来自第 6.7.9 节(初始化):
3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.
关于c - 半动态分配代码在 C++ 中有效,但在 C 中无效,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43030335/