How to define the size of an array using variables in C language?
In C language, the size of an array must be a constant expression and cannot be defined using a variable. This is because arrays require memory allocation at compile time, while variable values can only be determined at runtime, making it impossible to use variables to define the size of an array.
If you need to determine the size of an array based on the value of a variable, you can use dynamic memory allocation. You can achieve this by using the malloc function to dynamically allocate memory and using the variable’s value to determine the size of the allocation. Below is an example code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int size;
printf("请输入数组的大小:");
scanf("%d", &size);
int *array = (int*) malloc(size * sizeof(int));
if (array == NULL) {
printf("内存分配失败\n");
return 1;
}
for (int i = 0; i < size; i++) {
printf("请输入第%d个元素的值:", i+1);
scanf("%d", &array[i]);
}
printf("数组的元素为:");
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
free(array);
return 0;
}
In the above code, the size of the array was first obtained from the user, and memory space of corresponding size was dynamically allocated using the malloc function. Then, a loop structure was used to obtain the values of the array elements from the user input. Finally, the elements of the array were outputted and the memory space previously allocated was freed using the free function.