gpt4 book ai didi

c - 半动态分配代码在 C++ 中有效,但在 C 中无效,为什么?

转载 作者:太空宇宙 更新时间:2023-11-04 01:20:54 26 4
gpt4 key购买 nike

以下两段代码在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 a sizeof 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com