Search code examples
carraysdynamic-arraysuser-defined-types

User defined types with dynamic size in C


I want to define a new data type consisting of an array with a size inputted by the user. For example if the user inputs 128, then my program should make a new type which is basically an array of 16 bytes. This structure's definition needs to be global since I am going to use that type thereafter in my program. It is necessary to have a dynamic size for this structure because I will have a HUGE database populated by that type of variables in the end.

The code I have right now is:

struct user_defined_integer;
.
.
.
void def_type(int num_bits)
{
    extern struct user_defined_integer 
    {
             int val[num_bits/sizeof(int)];
    };

return;

}

(which is not working)

The closest thing to my question, I have found, is in here: I need to make a global array in C with a size inputted by the user (Which is not helpful)

Is there a way to do this, so that my structure is recognized in the whole file?


Solution

  • When doing:

    extern struct user_defined_integer 
    {
             int val[num_bits/sizeof(int)];
    };
    

    You should get the warning:

    warning: useless storage class specifier in empty declaration 
    

    because you have an empty declaration. extern does not apply to user_defined_integer, but rather the variable that comes after it. Secondly, this won't work anyway because a struct that contains a variable length array can't have any linkage.

    error: object with variably modified type must have no linkage
    

    Even so, variable length arrays allocate storage at the point of declaration. You should instead opt for dynamic memory.

    #include <stdlib.h>
    
    typedef struct
    {
        int num_bits;
        int* val;
    } user_defined_integer;
    
    void set_val(user_defined_integer* udi, int num_bits)
    {
        udi->num_bits = num_bits;
        udi->val = malloc(num_bits/sizeof(int));
    }