# Thread: Dynamic array of pointers

1. ## Dynamic array of pointers

I want to change the structure of a code from array of structs to struct of arrays. So I changed this part (arrays are declared dynamically) :
Code:
```float *velxl, *velyl,*childl;

int inc = some_value;
int i;
velxl = (float *)&childl[0*inc];
velyl = (float *)&childl[1*inc];```
To this:
Code:
```struct body { float velxd, velyd;};
body *nbodiesl;
for(i=0;i<something;i++){
nbodiesl[i].velxd = (float *)&childl[0*inc+i];
nbodiesl[i].velyd = (float *)&childl[1*inc+i];
}```
I know the last two lines are wrong, ( I think nbodiesl should be defined as an array of pointers to the struct instead of an array of structs ) but I don't know how to do it in C.
I appreciate if you could come up with an alternative solution, too.

Thanks

2. Originally Posted by rohams
I want to change the structure of a code from array of structs to struct of arrays.
I have no idea what you mean by this.
Originally Posted by rohams
So I changed this part (arrays are declared dynamically) :
Code:
```float *velxl, *velyl,*childl;

int inc = some_value;
int i;
velxl = (float *)&childl[0*inc];
velyl = (float *)&childl[1*inc];```
To this:
Code:
```struct body { float velxd, velyd;};
body *nbodies;
for(i=0;i<something;i++){
nbodiesl[i].velxd = (float *)&childl[0*inc+i];
nbodiesl[i].velyd = (float *)&childl[1*inc+i];
}```
I know the last two lines are wrong, ( I think nbodies should be defined as an array of pointers to the struct instead of an array of structs ) but I don't know how to do it in C.
I appreciate if you could come up with an alternative solution, too.

Thanks
In actual words, not code, what is it you are trying to do? nbodies as you have it is just a pointer to a structure. That means you have to dynamically allocate a structure and make nbodies point at it, or you have to make it hold the address of a non-dynamic struct you already have some place. In your example, it doesn't point anywhere specific, so you are likely going to crash as soon as you try to access it.

Quzah.

3. You've gone from an array of no-structs-at-all to an array of structs. If you really want a struct of arrays, then you would need to define the arrays (or the pointers, if you use dynamically allocated memory) inside the struct definition.