c语言

c语言怎么定义变长数组

小亿
82
2024-09-03 22:10:09
栏目: 编程语言

在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函数释放分配的内存。

0
看了该问题的人还看了