在C語(yǔ)言中,可以通過(guò)malloc函數(shù)或者calloc函數(shù)來(lái)創(chuàng)建動(dòng)態(tài)數(shù)組。
#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!\n");
return 0;
}
printf("Enter the elements of the array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("The elements of the array are:\n");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
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!\n");
return 0;
}
printf("Enter the elements of the array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("The elements of the array are:\n");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
return 0;
}
無(wú)論是使用malloc還是calloc函數(shù)創(chuàng)建動(dòng)態(tài)數(shù)組,都需要注意釋放內(nèi)存的操作,可以使用free函數(shù)釋放動(dòng)態(tài)數(shù)組占用的內(nèi)存空間。