I have an array of structs, which is dynamically allocated. A pointer to this array is passed around to other functions.
struct body{
char* name;
double mass;
// ... some more stuff
};
body *bodies = malloc(Number_of_bodies*sizeof(body));
I need to know the size of the array, so I'm storing the size in one of the structs, which is in the 0th element of the array (the first struct).
bodies[0].mass = (double)Number_of_bodies;
I then return from the function a pointer to the 1st element of the array i.e bodies[1]
return (bodies+1);
Now, when I use this pointer in other functions, the data should start at the 0th element.
body *new_bodies = (bodies+1); //Just trying to show what happens effectively when i pass to another function
new_bodies[0] = *(bodies+1); //I Think
If I want to see the initial struct, which was at bodies[0]
, does that mean in other functions I have to access new_bodies[-1]
?
Is this something I can do? How can I access the initial struct?
Yes, you can use
new_bodies[-1]
to access the initial element of the array. This is perfectly legal.The reason behind this is pointer arithmetic: square brackets is another way of writing
+
, so when you writenew_bodies[-1]
it is the same as*(new_bodies-1)
.Since
new_bodies
has been obtained asbodies+1
,new_bodies-1
is(bodies+1)-1
, orbodies
, makingnew_bodies[-1]
identical tobodies[0]
.Note: It looks like you are trying to shoehorn the number of elements into the initial element of the array of your
struct
s, re-purposing themass
field for it. This will work, but it is suboptimal, both in terms of memory allocation (a pointername
remains unused) but most importantly in terms of readability. You would be a lot better off using a flexible array member in astruct
that stores the number of entries explicitly:Here is a link to another Q&A with an example of working with flexible array members.