简体   繁体   中英

Is initializing an array of size 2 the same as mallocing a pointer with an array of size 2?

In my program, I'm creating an array of structs that's basically a value with a buffer of 32 bytes, or a struct that looks like:

typedef struct 
{
    long buffer[2];
    int val;
} buffered_val_t;

So each array value will have this buffer and a val. The idea behind this is to clear some space in a 64-byte cache line. However, instead of setting buffer[2] outright, is this equivalent to setting the struct as:

typedef struct 
{
     long * buffer;
     int val;
} buffered_val_t;

And then in another function, initializing buffer with:

long *array_one = (long *) malloc (sizeof(long) * 2);

int x;
for (x = 0; x < n; x++)
{
     buffered_val_t[x].buffer = array_one;
}

Would the same "buffer effect" be achieved here? Edit: by which I mean, will the same amount of space be cleared in the same parts of the cache?

Functionally same? Yes, they're both valid and achieve the same thing.

With the latter, you may have the additional work that you may want to free the malloc'ed memory regions.

On the other hand, if your array is too big, malloc 'ing - dynamic memory allocation - might be unavoidable because of the potential stack (aka, automatic storage) overflow issue. In your case, I'd suggest to stick with the former as it's only an array of 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM