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.
No --
list
is a pointer to an address in the heap, which is the start of a memory chunk that has sizesizeOfA * sizeof(A)
.list[i]
is the same thing as*(list + i)
, which is a dereference that will give you an actualA
.However..
Yup.
After this statement:
list
is a pointer to the starting location of a memory block that can holdsizeOfA
elements of typestruct A
. Thus,*list
is of typestruct A
, and similarly,list[i]
is of typestruct A
, not pointer tostruct A
(that would belist+i
).If you want
list[i]
to be a pointer tostruct A
, then your second piece of code would be the correct one, since you're allocating a memory location with enough space to holdsizeOfA
pointers tostruct A
. Note that you are only allocating space to hold pointers, not actualstruct A
instances. Attempting to readlist[i]->c
will result in undefined behavior.