开发者

Dynamic array of ints or not?

If I create a struct in one class as so

typedef struct
{     
    int numberOfTiles;
    // an array of ints here
    i开发者_StackOverflow中文版nt *tileArray; 

} CollisionLayer;

is it possible to create an array of ints with an empty [] and set the size on creation? Or how would this array be created? dynamically with a pointer? I will know the size of the array when creating one of these struct "objects", if it is possible to fill in the size of the array on creation, how is the array declared in the struct above?


You will need to initialize the array yourself:

CollisionLayer layer;
layer.numberOfTiles = numberOfTiles;
layer.tileArray = (int*)malloc(sizeof(int) * numberOfTiles);

Or, if you want to create the struct on the heap:

CollisionLayer* pl  = (CollisionLayer*)malloc(sizeof(CollisionLayer));
pl->numberOfTiles = numberOfTiles;
pl->tileArray = (int*)malloc(sizeof(int) * numberOfTiles);

// When you are done:
free(pl->tileArray);
free(pl);

The other option would be to hardcode a fixed size limit into CollisionLayer, e.g.:

typedef struct
{     
    int numberOfTiles;
    // an array of ints here
    int tileArray[100]; 

} CollisionLayer;

Of course this will be less desirable in all respects, but it's your only option if you don't want to manage memory manually.


If you don't know the size at compile time, then you must allocate the memory using malloc() at runtime. To use an actual array in C, you must know the size when the code is compiled.


tileArray is a pointer to int. malloc/calloc should be used to create the object to which it will point to. This should happen when creating an object of CollisionLayer.

Defining a struct in which the array [] is empty is not a good idea, refer this. It speaks of C++, bit it should apply for C as well.


VLAs cannot be members of structs so you will need to allocate the memory with malloc when you create the struct object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜