简体   繁体   中英

Array of pointers to struct in C

I have a struct in my c code of about 300Bytes (5xint + 256chars), and I wish to have a good mechanism of array for handling all my 'objects' of this struct. I want to have a global array of pointers, so that at first all indices in the array points to NULL, but then i initialize each index when I need it (malloc) and delete it when im done with it (free).

typedef struct myfiles mf;
mf* myArr[1000];

Is that what Im looking for? Pointers mixed with arrays often confuse me. If so, just to clerify, does

mf myArr[1000];

already allocates 1000 structs on the stack, where my first suggestion only allocates 1000pointers?

You are correct. Former allocates 1000 pointers, none of which are initialized, latter initializes 1000 objects of ~300 bytes each.

To initalize to null: foo_t* foo[1000] = {NULL};

But this is still silly. Why not just mf* myArr = NULL ? Now you have one pointer to uninitialized memory instead of 1000 pointers to initialized memory and one pointer to keep track of. Would you rather do

myArraySingle = malloc(sizeof(mf)*1000); or

for(int i = 0; i < 1000; i++) {
    myArray[i] = malloc(1000);
}

And access by myArraySingle[300] or *(myArray[300])`? Anyway my point is syntax aside don't create this unnecessary indirection. A single pointer can point to a contiguous chunk of memory that holds a sequence of objects, much like an array, which is why pointers support array-style syntax and why array indices start at 0.

typedef struct myfiles mf;
mf* myArr[1000];

This is what you are looking for. This will allocate array of 1000 pointers to the structure mf.

You seem to understand correctly.

More accurately, I believe mf* myArr[1000] = { 0 }; would better meet your requirements, because you want a guarantee that all of the elements will be initialised to null pointers. Without an initialisation, that guarantee doesn't exist.

There is no "global" in C. You're referring to objects with static storage duration, declared at file scope.

typedef struct myfiles mf;
mf* myArr[1000];

yes, it will initialize 1000 pointers, you have to allocate memory to each one using malloc/calloc before use.

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