开发者

C - Visually Efficient Pointer Array Initialization Using {}

开发者 https://www.devze.com 2023-03-24 13:45 出处:网络
Is there a way to do something like the array initialization braces method for a pointer array? myStruct* array = malloc(4*sizeof(myStruct));

Is there a way to do something like the array initialization braces method for a pointer array?

myStruct* array = malloc(4*sizeof(myStruct));
array = {a,b,c,d}; //like this

The reason I'm interested is because the af开发者_如何学JAVAorementioned lines are much nicer to look at than:

myStruct* array = malloc(4*sizeof(myStruct));
array[0] = blah0;
array[1] = blah1;
array[2] = blah2;
...
array[n] = blahn;

The variables I'm initializing to are variables passed as function arguments so I'm unable to efficiently iterate through them to initialize the array...


I think you can do it with C99. The feature is called "compound literals".

struct tag {
    int x;
    int y;
    int z;
};

struct tag *t;
t = &(struct tag){1, 2, 3};

Or, for arrays:

int *arr;
arr = (int []) {1, 2, 3};


If this is really about constant sized data as you indicate in your example, you probably simply shouldn't use malloc for it. C has arrays, use them :)

myStruct array[4] = {a,b,c,d};


Yes, but use them only needed:

myStruct array[] = {a,b,c,d};
0

精彩评论

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