How do you initialize a dynamic array in C language?
In C language, dynamic arrays are initialized by allocating memory using the malloc function, and assigning the first address of the array to a pointer variable. An example code is shown below:
#include <stdio.h>
#include <stdlib.h>
int main() {
int size;
printf("请输入动态数组的大小:");
scanf("%d", &size);
int *arr = (int*)malloc(size * sizeof(int));
if (arr == NULL) {
printf("内存分配失败\n");
return 1;
}
// 初始化数组
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
// 输出数组元素
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 释放动态数组内存
free(arr);
return 0;
}
In the above code, first the size of the dynamic array is obtained from user input using the scanf function. Next, memory space of size * sizeof(int) is allocated using the malloc function, and its starting address is assigned to a pointer variable of type int, arr. Then, the array is initialized using a for loop, setting the values of array elements to the index value plus 1. Finally, the memory space of the dynamic array is released using the free function.