在C语言中,有三种常见的方法来定义数组:
int arr[5]; // 定义一个包含5个整数的数组 这种方法在编译时确定数组的大小。数组的大小是固定的,不能在运行时更改。
malloc或calloc)定义数组:#include <stdlib.h> int* arr; int size = 5; arr = (int*) malloc(size * sizeof(int)); // 使用malloc分配内存 // 或者 arr = (int*) calloc(size, sizeof(int)); // 使用calloc分配并初始化为0 这种方法在运行时确定数组的大小。你可以根据需要调整数组的大小,但请注意,在使用完数组后,需要使用free()函数释放内存。
int size = 5; int arr[size]; // 定义一个包含5个整数的数组 这种方法允许在运行时确定数组的大小。请注意,VLA的大小在运行时是固定的,不能在运行时更改。同时,VLA在栈上分配内存,因此可能会导致栈溢出。