0

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]; | ^~~~~

  • nope.. the size of an array must be a constant and known by the compiler at compilation time.... use another dataContainer – ΦXocę 웃 Пepeúpa ツ Jun 10 '22 at 07:26
  • Don't use global variables just for the heck of it. Moving it inside main() would solve all your problems and would also be better design. – Lundin Jun 10 '22 at 09:33

2 Answers2

1

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
}
Frankie_C
  • 4,764
  • 1
  • 13
  • 30
0

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;
}
klutt
  • 30,332
  • 17
  • 55
  • 95