I am trying to use an array of pointers to a struct that has a pointer in it to another struct that is being used with an array of pointers.
I can write the code for a two single structs and it works. However, I am not sure how to deal with the introduction of the array of pointers. Sample code:
typedef struct { double vx; } particle_t; typedef struct { int m; int n; particle_t *inparticles; // Pointer to particles inside grid } grid_t; particle_t *particles = (particle_t*) malloc( 3 * sizeof(particle_t) ); grid_t *grid = (grid_t*) malloc( 3 * sizeof(grid_t) ); // trying 3 pointers if( particles==NULL || grid==NULL ){ puts("Unable to allocate memory"); exit(1);} // fill the structure grid[1].inparticles = particles[1]; // I am not sure how to link these grid[2].inparticles = particles[2]; // these lines give incompatible types error grid[3].inparticles = particles[3]; grid[1].m = 5; grid[1].n = 3; grid[1].inparticles -> vx = 15; Thank you in advance!
Update:
I realized that what I should be doing is use the inparticles pointer to point to multiple particles in the same grid pointer? How I can change the code so I can be able to do that? for example:
grid[0].inparticles[0] = particles[0]; grid[0].inparticles[1] = particles[1]; grid[0].inparticles[2] = particles[2]; declare it as an array somehow? would I need memory allocation for it as well?
https://stackoverflow.com/questions/66576699/how-to-use-multiple-pointers-to-a-struct-that-contains-a-pointer-to-another-stru March 11, 2021 at 12:55PM
没有评论:
发表评论