0

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.

Mike John
  • 818
  • 4
  • 11
  • 29
  • 1
    Ewww. Sorry but this code is horrible. First, one [must not cast the return value of `malloc()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858). Second, the variable name `sizeOfA` is an extremely bad choice, especially when used in conjunction with `sizeof A`. Furthermore, use `sizeof(*pointer)` instead of `sizeof(TYPE)` to be safe in case the base type of the pointer ever changes. All in all, the proper way to write that line would be `A *list = malloc(list_length * sizeof(*list));` –  Oct 19 '13 at 08:47
  • is list_length just my sizeOfA variable with a different name? – Mike John Oct 19 '13 at 08:53
  • 1
    Yes it is -- it's just a more descriptive and less confusing name. (Still feel free to write it as `listLength` if you prefer camel case.) –  Oct 19 '13 at 08:54
  • Yeah I prefer camel case. I like what you have just taught me, much better indeed. Thanks. – Mike John Oct 19 '13 at 08:55

2 Answers2

2

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.

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
0
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.

yamafontes
  • 5,552
  • 1
  • 18
  • 18
  • 1
    Right, but the latter being useless until it is actually filled with valid pointers. Only then they can be used. – glglgl Oct 19 '13 at 10:06