Home > Mobile >  Unable to allocate array based on char array length in C
Unable to allocate array based on char array length in C

Time:11-13

Getting some trouble with a function in C that basically creates and allocates a temporary array with help of the length of the name parameter extension length.

int my_func(char *name)
{
    char *extension = ".db";
    size_t tmp_size = strlen(name)   strlen(extension);
    char tmp_name[tmp_size];
    
    return 0;
}

This does not however seem to work on MSVC but works fine on Clang or GCC. Any idea why I get these errors:

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'tmp_name': unknown size

When I use the debugger in Clang on macOS I see that it allocates and work fine. Why not for MSVC?

CodePudding user response:

tmp_name is a variable length array, and such arrays are not supported in MSVC.

If you want this to work under MSVC you'll need to allocate space dynamically.

Also, your array is one element short as it doesn't have room for the terminating null byte for the combined string.

CodePudding user response:

Since tmp_size is a variable and not a fixed value you will have to allocate memory dynamically by using malloc you can also free the memory when you are done with it by using free.

Note: You will have to include stdlib header file to be able to access malloc and free functions

#include <stdlib.h>
#include <string.h>

int my_func(char *name)
{
    char *extension = ".db";
    size_t tmp_size = strlen(name)   strlen(extension);
    char *tmp_name;

    tmp_name = malloc(sizeof(*tmp_name) * tmp_size   1 );
    
    
    return 0;
}

To Free The Memory After You Done Using The Array*

free(tmp_name);
  •  Tags:  
  • c
  • Related