0

I've got a linked list (Tproduct) and I want to create an array of pointers to this, e.g.:

e1 -> e2 -> e3 -> e4 -> e5 -> e6
|           |                 |
v           v                 v
p[0]       p[1]              p[2]

My declaration looks like this:

Tproduct *arrayOfPointers = (Tproduct*)malloc(N*sizeof(Tproduct*));

Is this proper? I'm not sure if it's Tproduct *arrayOfPointers or Tproduct arrayOfPointers.

Regards.

1
  • 1
    Tproduct *arrayOfPointers says arrayOfPointers is pointer to Tproduct.Tproduct **arrayOfPointers says arrayOfPointers is pointer to Tproduct *. Commented Jun 25, 2013 at 8:58

1 Answer 1

5

If you want an array of pointers, you should do:

Tproduct **arrayOfPointers = (Tproduct**)malloc(N*sizeof(Tproduct*));

This code does exactly what you want - allocate memory for N Tproduct pointers.


What's wrong with your code?

  • Your type of arrayOfPointers is a pointer to Tproduct - so, you can manipulate it like1 an array of objects, but not like an array of pointers to the objects.

    1 It's still a pointer, not an array. That's why like.

  • In case you want an array of objects, you should allocate memory for N objects, not N pointers:

    malloc(N * sizeof(Tproduct))
    //                ^^^^^^^^ - Note: not a pointer
    

And now I want to write a function returning an array of this type. What's the prototype?

Tproduct** fill();

Should do the work. Example of function:

Tproduct** fill()
{
    Tproduct **arrayOfPointers = (Tproduct**)malloc(N*sizeof(Tproduct*));
    // do some stuff
    return arrayOfPointers;
}

But I suggest rename your function to, say, allocate_array or something like this. fill doesn't mean allocate.

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

2 Comments

and now I want to write a function returning an array of this type.. what's the prototype? Tproduct** fill(); Tproduct**[] fill(); Tproduct[]** fill(); are not working :/
TYPE* ptr = malloc(N * sizeof *ptr) is preferable ... shorter, more general, less coupling, no masking of undeclared malloc (which will default to int if the header is missing) ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.