我尝试了以下示例:
#include <stdio.h>
int main() {
const int a;
scanf("%d", &a);
int arr[a];
arr[20] = 1;
printf("%d", arr[20]);
}
输出:
20
1
答案 0 :(得分:5)
您可能正在寻找一种为阵列动态分配内存的方法。动态地表示要在执行程序期间确定要用于阵列的内存。实现此目标的一种非常合理的方法是使用stdlib.h中的malloc和free。这是一个非常简单的示例,说明了如何执行此操作。 (它还会填充数组,然后打印数组的元素)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
int *arr;
printf("Enter the amount that you would like to allocate for your array: ");
scanf("%d",&a);
/* Dynamically Allocate memory for your array
The memory is allocated at runtime -> during the execution
of your program */
arr = (int *)malloc(a * sizeof(int));
/* Check if the memory was allocated successfully
In case it wasn't indicate failure printing a message to
the stderr stream */
if (arr == NULL) {
perror("Failed to allocate memory!");
return (-1);
}
/* Populate the array */
for (int i = 0; i < a; i++) {
arr[i] = i;
}
/* Print each element of the array */
for (int i = 0; i < a; i++) {
printf("%d\t", arr[i]);
}
/* Free the memory once you no longer need it*/
free(arr);
return 0;
}
这里也是有关此主题的非常详细的信息:https://en.wikipedia.org/wiki/C_dynamic_memory_allocation
这是通过使用可变长度数组动态分配所需内存的另一种方法。
#include <stdio.h>
#include <stdlib.h>
static void vla(int n);
int main()
{
int a;
printf("Enter the amount that you would like to allocate for your array: ");
scanf("%d",&a);
/*vla stands for Variable Length Array*/
vla(a);
return 0;
}
static void vla(int n)
{
/*The correct amount of storage for arr is automatically
allocated when the block containing the array is entered
and the declaration of the arr is reached. This allows
you to use variables for array index which are not compile-time constants*/
int arr[n];
/* Populate the array */
for (int i = 0; i < n; i++) {
arr[i] = i;
}
/* Print each element of the array */
for (int i = 0; i < n; i++) {
printf("%d\t", arr[i]);
}
/*No need of using free since the storage is automatically
deallocated when leaving the block*/
return;
}
我也建议遵循一致的编码风格,以使您和其他人更容易理解您的代码。这是一份简短的指南,其中包含有关如何实现此目标的主要规则:https://developer.gnome.org/programming-guidelines/stable/c-coding-style.html.en