C言語で可変長配列を作成する方法
C言語では、malloc関数かcalloc関数を使用して動的配列を作成できる。
- malloc関数を用いて動的配列を作成する:
#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;
}
- 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 *)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;
}
malloc関数を用いるかcalloc関数を用いて動的配列を作成した場合、いずれにしてもメモリの解放処理が必要であり、free関数は動的配列が占有していたメモリ空間を解放するのに使用できる