c语言中动态数组如何创建
在C语言中,可以通过malloc函数还是calloc函数来创建动态数组。
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
arr = (int *)malloc(size * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!
");
return 0;
}
printf("Enter the elements of the array:
");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("The elements of the array are:
");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("
");
free(arr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
arr = (int *)calloc(size, sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!
");
return 0;
}
printf("Enter the elements of the array:
");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("The elements of the array are:
");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("
");
free(arr);
return 0;
}
不管是使用malloc或calloc函数创建动态数组,都需要注意释放内存的操作,可使用free函数释放动态数组占用的内存空间。
TOP