If I have a struct:
typedef struct A
{
char c[100];
}A;
Then I create a
sizeOfA = 5000;
A *list = (A*) malloc(sizeOfA * sizeof(A));
Is list[i]
a pointer to a struct?
Or if I want a pointer to the struct, should I do
A **list = (A**) malloc (sizeOfA * sizeof(A*);
[EDIT]
Now let's say I created the list using A *list
(which I did already). How would I create 5000 pointers and make them point to the elements on the list?
p0 -> list[0]
p1 -> list[1]
..
..
p[n] -> list[n]
After going back and forth a few times I noticed that for sorting the pointers help a lot.
To be fair I will post the edit above as a separate question.
After this statement:
A *list = (A*) malloc(sizeOfA * sizeof(A));
list
is a pointer to the starting location of a memory block that can hold sizeOfA
elements of type struct A
. Thus, *list
is of type struct A
, and similarly, list[i]
is of type struct A
, not pointer to struct A
(that would be list+i
).
If you want list[i]
to be a pointer to struct A
, then your second piece of code would be the correct one, since you're allocating a memory location with enough space to hold sizeOfA
pointers to struct A
. Note that you are only allocating space to hold pointers, not actual struct A
instances. Attempting to read list[i]->c
will result in undefined behavior.
A *list = (A*) malloc(sizeOfA * sizeof(A));
Is list[i] a pointer to a struct?
No -- list
is a pointer to an address in the heap, which is the start of a memory chunk that has size sizeOfA * sizeof(A)
. list[i]
is the same thing as *(list + i)
, which is a dereference that will give you an actual A
.
However..
A **list = (A**) malloc (sizeOfA * sizeof(A*);
Is list[i] a pointer to a struct?
Yup.