Home > Back-end >  How can I fix this? - global variable with size x
How can I fix this? - global variable with size x

Time:06-11

I always get a error by trying this. Isn't it possible to ask the user to enter the arraysize of a global variable / array? - The array has to be global.

#include <stdio.h>

// global 

int size = 1;
char array[size];

int main(){
    scanf("%d", &size);
}

OUTPUT: main.c:14:6: error: variably modified ‘array’ at file scope 14 | char array[size]; | ^~~~~

CodePudding user response:

You can't modify a statically allocated variable array.

You can however use the memory allocation functions to create and modify the array:

#include <stdio.h>

// global 

int size = 0;
char *array = NULL;

int main(){
    scanf("%d", &size);
    array = malloc(size);
    if (!array)
    {
        ... handle error.
    }
    scanf("%d", &size);    //ask a new dimension
    char *tmp = realloc(array, size);   //reallocate array keeping old data
    if (!tmp)    //reallocation failed
    {
        free(array);    //release memory
        ... handle error.
    }
    array = tmp;     //reassign new memory to the array pointer
}

CodePudding user response:

If you want to use a VLA, you can do it like this:

#include <stdio.h>

// global 

int size = 1;
char *array;

int main(){
    scanf("%d", &size);
    char a[size];
    array = a;
}
  • Related