声明静态数组会生成以下警告:ISO C90 forbids variable length array 'v' [-Wvla]

Declaration of static array generates the following warning: ISO C90 forbids variable length array 'v' [-Wvla]

下面的代码可以很好地保存和打印静态 5 分量数组。但是,我仍然收到一条警告,说我真的不知道如何修复:[Warning] ISO C90 forbids variable length array 'v' [-Wvla]。它来自声明向量的位置:float v[n]; 非常感谢对此的任何帮助。谢谢! :-)

#include <stdio.h>

void print_vector(int N, float * V);
void save_vector(int N, float * V);

int main(void)
{
    const int n = 5;
    float v[n];

    printf("Enter the %d components of the vector:\n", n);
    save_vector(n, v);

    puts("\nThe vector is:");
    print_vector(n, v);

    return 0;
}

void save_vector(int N, float * V)
{
    int i;
    for(i = 0; i < N; i++)
        scanf("%f", V+i);
}

void print_vector(int N, float * V)
{
    int i;
    for(i = 0; i < N; i++)
        printf(" %.2f ", V[i]);
}

这个数组:

float v[n];

被认为是可变长度数组,因为数组的大小不是编译时常量。声明的变量 const 不符合编译时常量的条件。

你可以做的是对大小使用预处理器宏

#define N 5
...
float v[N];

预处理器进行直接标记替换,因此 N 在这种情况下是一个编译时间常量。