如何创建一个动态数组?
我们可以用到malloc函数进行:
#include <stdio.h>
#include <stdlib.h>
int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
// 使用malloc()函数分配内存空间
int *array = (int*)malloc(size * sizeof(int)); #*创建
if (array == NULL) {
printf("Error: Memory allocation failed.\n");
return 1;
}
// 打印数组中的元素
for (int i = 0; i < size; i++) {
array[i] = i + 1;
printf("%d ", array[i]);
}
printf("\n");
// 释放内存空间
free(array);
return 0;
}
int *array = (int*)malloc(size * sizeof(int));
切记:要有释放空间的做法!
查看20道真题和解析
