1

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?

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Is it ok to depend on the fact that all pointers in my first suggestion are NULL, or it points to arbitrary location in the memory?
It would be better to do a memset on the array to ensure all pointers, point to NULL.
@e-r-a-n see edit, you can do this in one line since I think C99.
Why silly? I want to have clean start with my array, as I want to relay on the fact a spot in it is either null or storing a location for a struct
1
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.

Comments

1

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.

Comments

0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.