How to resolve a variable for char length? [closed]

You want a variable lenght array, you can do it like this:

int digit;
scanf("%d", &digit);
char test [digit+1];

This will work for your purposes. Usual restrictions of course apply.
Keep in mind this functionality was only added in the C99 Standard. So if your compiler supports only previous standards, this will not work.

However, the more appropriate and better practice method to use is to use malloc to allocate the char array properly

int digit;
scanf("%d", &digit);
char* aa = malloc(digit + 1);
//Do what you want with the char array aa
free(aa);

Do not forget to check the result of malloc() against NULL and free the variable afterwards to prevent memory leaks if you want to do this.

Also be aware that the “array” malloc returns is actually just a pointer, which is very relevant when trying to determine the size/length of it, using sizeof:

char real_array[5];
sizeof(real_array); // == 5

char* dynamic_array = malloc(5);
sizeof(dynamic_array) // == sizeof(char*) == on most systems = 8

Leave a Comment