gpt4 book ai didi

c - 声明数组时出现错误 : Constant expression required,,例如 a[n]

转载 作者:行者123 更新时间:2023-11-30 18:15:33 26 4
gpt4 key购买 nike

这里需要常量表达式,也就是说我们不能先输入n,然后像int a[n]那样声明数组。

我的代码是:

#include <stdio.h>
int main() {
int n;
scanf("\n Enter the no. of elements of the array. %d", n);
int a[n];
for(int i=0; i<n; i++)
scanf("\n Enter the elements of the array. %d", &a[i]);
for(int j=0; j<n; j++)
printf(" %d", a[j]);
return 0;
}

还请告诉我这是否是动态内存分配。如果是的话,那它和新的有什么不同。因为 new 也在运行时分配内存,这也是如此。

最佳答案

您的代码不是有效的 C90,而是有效的 C99。

可变长度数组不被视为动态内存分配,因为该术语用于指代基于堆的分配器(例如malloc())。但它们是动态的,因为分配的大小只能在执行时计算。

关于c - 声明数组时出现错误 : Constant expression required,,例如 a[n],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23875065/

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