Access element -1 of an array in c

I have an array of structures that is dynamically allocated. A pointer to this array is passed 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 save the size in one of the structures that is in the 0th element of the array (first structure).

 bodies[0].mass = (double)Number_of_bodies; 

Then I return from the function a pointer to the 1st element of the array ie bodies[1]

  return (bodies+1); 

Now, when I use this pointer in other functions, the data should start from 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 structure that was in bodies[0] , does this mean in other functions, do I need to access new_bodies[-1] ?

Can I do something? How can I access the original structure?

+5
source share
1 answer

Yes, you can use new_bodies[-1] to access the original element of the array. This is completely legal.

The reason for this is pointer arithmetic: square brackets are another way of writing + , so when you write new_bodies[-1] , it is the same as *(new_bodies-1) .

Since new_bodies was obtained as bodies+1 , new_bodies-1 is equal to (bodies+1)-1 or bodies , which makes new_bodies[-1] identical to bodies[0] .

Note It looks like you are trying to flip the number of elements into the original element of your struct s array by re-assigning the mass field to it. This will work, but it is suboptimal, both in terms of memory allocation (the name pointer remains unused), but most importantly in terms of readability. You would be much better off using the flexible member of an array in a struct that explicitly stores the number of records:

 struct body { char* name; double mass; // ... some more stuff }; struct bodies { size_t count; body bodies[]; // <<== Flexible array member }; ... bodies *bb = malloc(sizeof(bodies)+Number_of_bodies*sizeof(body)); bb->count = Number_of_bodies; 

Here is a link to another Q & A with an example of working with flexible array elements .

+11
source

Source: https://habr.com/ru/post/1206732/


All Articles