I have a function that is supposed to be creating structures and storing them in an array of structures.
Lets say this is my structure:
struct str {
...
};
The function takes a parameter that looks like this:
struct str **ptr
Which is a pointer to a pointer that points to a structure if I get it right and I am supposed to set this parameter to be pointing to the first element of the array of structures which will be the first structure in that array.
So, if the parameter looks like this, that means that instead of having just an array of structures, I have an array of pointers that point to that structure, right?
Now I have declared the array of pointers to structures like this:
struct str *structures[20];
because I am expecting to have 20 (pointers to )structures store there.
Then I have a loop that is allocating memory for the structures and is storing them in the array like this:
struct str *structure;
structure = malloc(sizeof(struct str));
Then I fill in the parameters of the structure I want like this:
structure->a = 1; structure->b = 2; .........
And I store it in the array like this:
structures[n] = structure;
And I make sure it is stored in the array at the position where I wanted it to be by printing a parameter from the structure each loop like this:
printf("%d\n", structures[7]->a);
My question is, how do I set the parameter of the function to be pointing to the first pointer to a structure in that array?
And did I get it right?
Also, the parameter needs to be taken from main.
And I need to work with these (pointers to)structures of the array outside this one function as well.
What will the parameter look like?
struct str *pointer;
?
Also, wouldn't it be possible to just point the pointer to the array itself and it should automatically be pointing to the first element in it?
So that I could then reference the nth member of the array via the pointer since I need to work with all of them later on?
I have looked at this thread, but I'm still a bit confused so I'd appreciate any feedback.