[英]Is it possible to declare an array using a variable?
Hi I was told during my first class about arrays in C that you cannot declare them using a variable, for example: int array[n]
.嗨,我在第一堂课上被告知 C 中的数组,您不能使用变量声明它们,例如:
int array[n]
。 Yet if I write a code like this:然而,如果我写这样的代码:
#include <stdio.h>
int main()
{
int n;
scanf("%d",&n);
int array[n];
}
Codeblocks doesn't give me any warning or error. Codeblocks 没有给我任何警告或错误。 How do I know that what I wrote isn't correct?
我怎么知道我写的不正确?
This is valid (since C99), although optional (since C11).这是有效的(自 C99 起),尽管是可选的(自 C11 起)。 More portable:
更便携:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
size_t n = 0;
int *array = NULL;
if ((scanf("%zu", &n) <= 0) ||
(n > SIZE_MAX / sizeof(*array)) ||
((array = malloc(n * sizeof(*array))) == NULL))
{
return EXIT_FAILURE;
}
// Use array
free(array); // Don't forget to free the memory.
}
Codeblocks doesn't give you an error or a warning, because there is none. Codeblocks 不会给你一个错误或警告,因为没有。 You can do the declaration with no problem since C99.
自 C99 以来,您可以毫无问题地进行声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.