I am trying to modify a struct that is a pointer inside of another struct within a function and then have the change reflect back outside of the function.
I have simplified my code below to the exact issue I am having. I understand that inside my function, as currently constructed, I am modifying the value of x, rather than the utilizing the address of x to modify, but I can't seem to wrap my head around how to properly modify each particle in the array. I have tried
b[0].p->x++;
inside the for loop in the test function, but that only changes p[0] from 1 to 5.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int x;
} particle_t;
typedef struct {
int num_part;
particle_t* p;
} bins;
void test (bins *b) {
for (int i = 0; i < 4; i++) {
b[0].p[i].x++;
}
}
int main (int argc, char **argv) {
particle_t *particles = (particle_t*) malloc (4 * sizeof(particle_t));
particles[0].x = 1;
particles[1].x = 2;
particles[2].x = 3;
particles[3].x = 4;
bins *b = (bins*) malloc (4 * sizeof(bins));
b[0].num_part = 1;
b[0].p = (particle_t*) malloc (4 * sizeof(particle_t));
for (int i = 0; i < 4; i++) {
b[0].p[i] = particles[i];
}
test(b);
printf("%d %d %d %d\n",particles[0].x,particles[1].x,particles[2].x,particles[3].x);
return 0;
}
After running the test function, I expected that printing out particles[i].x would yield 2, 3, 4, and 5, but I am still receiving 1, 2, 3, and 4.
testfunction, I expected that" - the program terminates after running thetestfunction...printfline, sorry! updated!int main (int argc, char **argv)To avoid the compiler outputting two warning messages about unused parameters, When the parameters tomain()are not used, then use the signature:int main( void )