Passing "BigStruct" to "SmallStruct" in C (similar structures with static arrays of different sizes)

It is assumed that for some reason you are allowed to use static memory in a C program. I have a basic structure that I use in several places defined below:

#define SMALL_STUFF_MAX_SIZE 64 typedef struct { /* Various fields would go here */ ... double data[SMALL_STUFF_MAX_SIZE]; /* array to hold some data */ } SmallStuff; 

Now I was asked to add a new function that will lead to a specific case when I need the same structure, but with a much larger array. I cannot afford to grow the SmallStuff structure array, because the memory is too tight. Therefore, I made a special version of the structure described below, which I eventually contributed to (SmallStuff *) when calling functions that expect a pointer to the SmallStuff structure (the actual size of the "data" is properly processed in these functions)

 #define BIG_STUFF_MAX_SIZE 1000000 typedef struct { /* Various fields, identical to the ones in SmallStuff would go here */ ... double data[BIG_STUFF_MAX_SIZE]; /* array to hold some data */ } BigStuff; 

Obviously, the correct way to do this would be to dynamically allocate memory, but as said above, I cannot use dynamic memory allocation.

Are there any side effects that I should consider? Or more effective ways to solve this problem?

Thanks in advance.

+4
source share
3 answers

What you do is good, although it usually scares people who are uncomfortable with pointers and castings.

The general solution for your problem is to get rid of BigStuff and SmallStuff and create a single Stuff structure with a size member and double * data that points to the array you selected, and not risk potential errors in your code later or you need to change your functions when you find that you also need MediumStuff. This gives you the flexibility to use any size.

 typedef struct { // the usual size_t data_length; double *data; } Stuff; double bigdata[BIG_STUFF_MAX_SIZE]; Stuff big = { ..., BIG_STUFF_MAX_SIZE, bigdata }; 
+3
source
 typedef struct { /* Various fields would go here */ double data[]; /* a flexible array (C99 extension) */ } AnySizeStuff; typedef struct { AnySizeStuff header; double smalldata[SMALL_STUFF_MAX_SIZE]; } SmallStuff; typedef struct { AnySizeStuff header; double bigdata[BIG_STUFF_MAX_SIZE]; } BigStuff; 

Then, if x is either SmallStuff or BigStuff, you can pass & x.header to routines that can accept either.

+1
source

Despite its ugly code due to complexity, there shouldn't be any run-time problems, since the sizes are hard-coded.

The best way to handle this is to have algorithms that you don't need to have two separate structures that differ only in size. However, I do not know your application, so you better know how to deal with this problem.

0
source

All Articles