简体   繁体   中英

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

The below code works just fine to save and print a static 5-component array. However, I am still getting a warning that I don't really know how to fix: [Warning] ISO C90 forbids variable length array 'v' [-Wvla] . It comes from where the vector is declared: float v[n]; Any help on this one would be very much appreciated. Thank you: :-)

#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]);
}

This array:

float v[n];

Is considered a variable length array because the size of the array is not a compile time constant. Variables declared const do not qualify as a compile time constant.

What you can do instead is use a preprocessor macro for the size

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

The preprocessor does direct token substitution, so N is a compile time constant in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM