当前位置: 动力学知识库 > 问答 > 编程问答 >

Casting a 'BigStruct' to a 'SmallStruct' in C (similar structs with static arrays of different sizes)

问题描述:

Supposed that for some reason you are only allowed to use static memory in a C program.

I have a basic structure that I am using in several places defined as 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 have been asked to add a new feature that lead to a particular case where I need the same structure but with a much larger array. I can't afford to max up the array of the SmallStuff structure as memory is too tight. So I made a special version of the struct defined as below that I eventually cast to a (SmallStuff*) when calling functions that expect a pointer to a SmallStuff structure (the actual size of 'data' is properly handled 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 proper way to do it would be to dynamically allocate the memory but as said above I can't use dynamic memory allocation.

Are there any side-effects that I should consider?

Or better ways to deal with this kind of problem?

Thanks in advance.

网友答案:

What you're doing is fine, though it tends to scare people who are uncomfortable with pointers and casting.

The general solution for your problem is to get rid of BigStuff and SmallStuff and make a single Stuff structure with a size member and a double *data that points to an array of your choosing, instead of risking potential miscasts in your code later or having to change your functions when you discover you also need MediumStuff. This gives you the flexibility of using whatever sizes are appropriate.

typedef struct
{
  // the usual

  size_t data_length;
  double *data;
} Stuff;


double bigdata[BIG_STUFF_MAX_SIZE];
Stuff big = { ..., BIG_STUFF_MAX_SIZE, bigdata };
网友答案:
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 a SmallStuff or BigStuff, you can pass &x.header to routines that can take either.

网友答案:

Although its ugly code because of the complexity, there should not be any runtime problems because the sizes are hard-coded.

A better way to deal with it is to have algorithms which didnt need you to have 2 separate structs which only differ by size. However, I dont know your application, so you know best how to deal with this problem.

分享给朋友:
您可能感兴趣的文章:
随机阅读: