csand
csand

Reputation: 11

Dynamically create an array of TYPE in C

I've seen many posts for c++/java, but nothing for C. Is it possible to allocate memory for an array of type X dynamically during run time? For example, in pseudo,

switch(data_type) 
     case1:float, create a new array of floats to use in the rest of the program
     case2:int, create new array of ints to use in the rest of the program
     case3:unsigned, ....
     // etc.

In my program I determine the data type from a text header file during run time, and then I need to create an appropriate array to store/manipulate data. Is there some kind of generic type in C?

EDIT: I need to dynamically create and DECIDE which array should be created.

Thanks, csand

Upvotes: 1

Views: 1679

Answers (2)

Craig Putnam
Craig Putnam

Reputation: 101

You're going to have a hard time doing this in C because C is statically typed and has no run-time type information. Every line of C code has to know exactly what type it is dealing with.

However, C comes with a nifty and much-abused macro preprocessor that lets you (among other things) define new functions that differ only in the static type. For example:

#define FOO_FUNCTION(t) t foo_function_##t(t a, t b) { return a + b; }

FOO_FUNCTION(int)
FOO_FUNCTION(float)

This gets you 2 functions, foo_function_int and foo_function_float, which are identical other than the name and type signature. If you're not familiar with the C preprocessor, be warned it has all sorts of fun gotchas, so read up on it before embarking on rewriting chunks of your program as macros.

Without knowing what your program looks like, I don't know how feasible this approach will be for you, but often the macro preprocessor can help you pretend that you're using a language that supports generic programming.

Upvotes: 0

Gavin H
Gavin H

Reputation: 10482

Assuming you calculate the total size, in bytes, required from the array, you can just allocate that much memory and assign it to the correct pointer type.

Ex:

void * data_ptr = malloc( data_sz );

then you can assign it to a pointer for whatever type you want:

int *array1 = (int *)data_ptr;

or

float *array2 = (float *)data_ptr;

NOTE: malloc allocates memory on the heap, so it will not be automatically freed. Make sure you free the memory you allocate at some point.

UPDATE

enum {
    DATA_TYPE_INT,
    DATA_TYPE_FLOAT,
    ...
};

typedef struct {
    int data_type;
    union {
        float * float_ptr;
        int * int_ptr;
        ...
    } data_ptr;
} data;

While this might allow you to store the pointer and tell what type of pointer you should be using, it still leaves the problem of not having to branch the behavior depending on the data type. That will be difficult because the compiler has to know the data type for assignments etc.

Upvotes: 5

Related Questions