在C语言中,要定义一个变长数组(VLA),需要使用动态内存分配。这是因为C语言不支持变长数组作为函数参数或返回值。以下是如何定义和使用变长数组的示例:
#include<stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
// 使用malloc分配内存空间
int *vla = (int *) malloc(n * sizeof(int));
if (vla == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &vla[i]);
}
printf("The entered elements are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", vla[i]);
}
printf("\n");
// 释放分配的内存
free(vla);
return 0;
}
在这个示例中,我们首先从用户那里获取数组的大小(n
),然后使用malloc
函数为变长数组分配内存。接下来,我们将用户输入的元素存储在变长数组中,并打印出这些元素。最后,我们使用free
函数释放分配的内存。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:c语言可变长数组怎样定义