I want to define a new data type consisting of an array with the size entered by the user. For example, if the user enters 128, then my program should create a new type, which is basically an array of 16 bytes.
This is not possible in C because C types are compilation time and do not exist at all at run time.
However, with a compiler complying with C99, you can use a flexible array element. You will need a struct containing some elements and ending in an array without any specific dimension, for example
struct my_flex_st { unsigned size; int arr[];
Here is a way to highlight it:
struct my_flex_st *make_flex(unsigned siz) { struct my_flex_st* ptr = malloc(sizeof(struct my_flex_st) + siz * sizeof(int)); if (!ptr) { perror("malloc my_flex_st"); exit(EXIT_FAILURE); }; ptr->size = siz; memset (ptr->arr, 0, siz*sizeof(int)); return ptr; }
Do not forget free , as soon as you no longer use it.
Of course, you will need to use pointers in your code. If you really want to have a global variable, declare it, for example,
extern struct my_flex_st* my_glob_ptr;
source share