How to customize the length of an array in C language?
In C language, the length of an array is determined at the time of array definition and cannot be dynamically defined at runtime. To customize the length of an array, one can use pointers and dynamic memory allocation.
One way is to use the malloc function to dynamically allocate memory, and then assign the returned pointer to an array pointer variable. An example code is shown below:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("请输入数组长度: ");
scanf("%d", &n);
// 动态分配内存
int* arr = (int*)malloc(n * sizeof(int));
// 使用数组
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
}
// 打印数组
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// 释放内存
free(arr);
return 0;
}
Another method is using variable length arrays (VLA), a feature introduced in the C99 standard. Here is an example code:
#include <stdio.h>
int main() {
int n;
printf("请输入数组长度: ");
scanf("%d", &n);
// 定义可变长度数组
int arr[n];
// 使用数组
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
}
// 打印数组
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
It is important to note that when using variable-length arrays, the array length must be a variable rather than a fixed constant. Additionally, the memory for variable-length arrays is allocated on the stack, not on the heap. Therefore, if the array length is too large, it may lead to a stack overflow issue.