数组在C不定长 [英] Array with undefined length in C
本文介绍了数组在C不定长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看在我的课本练习,上面写着:创建一个从键盘长度N阵列
i was watching an exercise in my textbook that says: Create a C program that take from the keyboard an array with length "N".
现在的问题是:在C语言中,如何创建一个未定义长度的数组?
The question is: In C language, how can i create an undefined length array?
感谢大家。
推荐答案
不要创建不定长的数组。
Do not create an array of undefined length.
的之后的获得所需要的长度 N
,如果C99使用VLA(可变长度数组)
After getting the needed length N
, if C99 use a VLA (Variable Length Array)
int A[N];
...或分配内存
... or allocate memory
int *A = malloc(sizeof *A * N);
...
// use A
...
free(A);
向好,然后再继续对 N
添加验证。例如:
Good to add validation on N
before proceeding. Example:
if (N <= 0 || N >= Some_Sane_Upper_Limit_Like_1000) return;
这篇关于数组在C不定长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文