Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
na1368 Avatar asked Aug 26 '14 06:08

na1368


People also ask

What are user-defined data types in C?

A user-defined data type (UDT) is a data type that derived from an existing data type. You can use UDTs to extend the built-in types already available and create your own customized data types.

Is array size dynamic in C?

Unlike other high-level languages (Python, JavaScript, etc), C doesn't have built-in dynamic arrays.

Are arrays dynamic in size?

One limitation of arrays is that they're fixed size, meaning you need to specify the number of elements your array will hold ahead of time. A dynamic array expands as you add more elements. So you don't need to determine the size ahead of time.

Can a user define the size of the array?

Yes if u want to set the size of the array at run-time. Then u should go for dynamic memory allocation(malloc/calloc).


1 Answers

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));
}
like image 171
user3977796 Avatar answered Sep 22 '22 03:09

user3977796