How to define dynamic arrays in C language?
In the C language, dynamic arrays are defined using pointers and memory space is allocated dynamically using the malloc function. Below is an example code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n; // 动态数组的大小
int *arr; // 动态数组的指针
printf("请输入动态数组的大小:");
scanf("%d", &n);
// 动态分配内存空间
arr = (int *) malloc(n * sizeof(int));
if (arr == NULL) {
printf("内存分配失败!\n");
return 1;
}
// 输入动态数组的元素
for (int i = 0; i < n; i++) {
printf("请输入第%d个元素:", i + 1);
scanf("%d", &arr[i]);
}
// 输出动态数组的元素
printf("动态数组的元素为:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// 释放动态数组的内存空间
free(arr);
return 0;
}
The code first uses the scanf function to get the size of a dynamic array, then allocates enough memory space using the malloc function. It then uses a for loop to input elements into the dynamic array and another for loop to output the elements. Finally, it uses the free function to release the memory space allocated for the dynamic array.