# Thread: malloc ing array's or structures

1. ## malloc ing array's or structures

I have a situation where I need to store a series of objects (they're actually 3d objects, so each structure will have an array of points/faces plus position/rotation info inside)

however I don't know how many objects there are, so I need to use malloc, And I'm getting really confused over what the syntax should be (or if I have the method totally wrong)

struct object
{
int *q;
};

//this curently is just a placeholder while I get the rest of it working, the pointer q just points to an array of floats.

struct object *p;

p=malloc(16*sizeof(struct object));

that is how I would expect to allocate an array of 16 structs to pointer p, however when I try to access it as an array, I get stuck

I think it should be something like

p[n]->q=malloc (16*sizeof(float));

to allocate an array of 16 floats to the pointer q in the nth structure of the array pointed to by p.

this just gives invalid argument of type "->" error. though I can't find any info on what I'm doing wrong (this is about then tenth attempt to get something working, there's probably something silly I'm missing, but I'm still a beginner so go easy on me.....

thanks
-mark

2. >>p[n]->q=malloc (16*sizeof(float));
It should be
Code:
`p[n].q = malloc(16*sizeof(float));`
since you're malloc'ing complete structures instead of pointers to structures :-)

3. ahhhhhh thankyou it works now...

could you explain one little thing.... I thought malloc returned a pointer to the memory, so why am I now accessing it this way.

and more importantly, why did the method I tried fail :S. earlier before I realised I'd need multiple structs, I used just had

struct object *p;
p->q=malloc (stuff);

and that worked fine

but in both cases, p is defined as a pointer..... erm

sorry for pestering

thanks
-mark

4. >> thought malloc returned a pointer to the memory, so why am I now accessing it this way
You only have one pointer, that's to the beginning of the memory. Imagine that you used an array instead
Code:
`struct object p[16];`
You'd access it with the . operator because each of those 16 objects is a struct, not a pointer to a struct. It would be completely different if you allocated the memory like this
Code:
```struct object **p;
p=malloc(16*sizeof(struct object *));```
Then you would have to allocate memory for each object because they're only pointers, but you would then access them with the -> operator.
Code:
```struct object *p;
..
p->q=malloc (stuff);```
That's like saying
Code:
```struct object *p;
..
p[0].q=malloc (stuff);```

5. thanks for clearing that up

-mark