Search code examples
arrayscpointerscharstring-length

C Set Array size by strlen()


In C, not C++, I tried to set a char array size using a strlen() contained in a const int.

char *input = "hello";

//now the integer that contains the lenght
static const int lengthA = strlen(input); //upto here, it works

char list_array[lengthA]; //here doesn't work, because the variable lengthA is not initialized

So, I want that the length of input is used as the length of the array.

I already tried with sizeof, instead of strlen, but it returns the byte

Is this possible?


Solution

  • The feature you're using is called a variable length array, where the size of an array is determined at runtime. However, Visual Studio does not support this feature.

    You'll need to allocate memory dynamically with malloc:

    char *input = "hello";
    static const int lengthA = strlen(input);
    char *list_array = malloc(lengthA);