声明一个具有非常量大小变量的数组 [英] Declaring an array with a non-constant size variable

查看:25
本文介绍了声明一个具有非常量大小变量的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 C 语言的测试,我正在阅读从某个网站下载的 C 摘要.写着不允许写arr[i],其中i是一个变量.唯一的方法是使用 malloc.
但是,我编写了以下代码,它在 valgrind 上编译时没有警告也没有错误:

I'm studying for my test in C and I'm reading in a C summary I downloaded from some site. It is written that it is not allowed to write arr[i] where i is a variable. The only way to do it is with malloc.
However, I wrote the following code and it compiles without warnings and without error on valgrind:

int index = 5;
int a4[index];

a4[0] = 1;
a4[1] = 2;

int index2;
scanf("%d",&index2);
int a5[index2];
a5[0] = 1;
a5[1] = 2;

那么数组声明背后的真相是什么?谢谢!

So what is the truth behind array declarations? thank you!

推荐答案

C99 允许 可变长度数组 要在堆栈上创建.您的编译器可能支持此功能.此功能在 C89 中不可用.

C99 allows variable length arrays to be created on the stack. Your compiler may support this feature. This features is not available in C89.

从某个角度来看,摘要告诉您的是真实的.:-)

What the summary told you was true, from a certain point of view. :-)

这篇关于声明一个具有非常量大小变量的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆