I have a ball that has 1 adjacent ball as shown in the code below. The problem I am facing is updating the ball 2 value which is stored in ball1 's adjacent, doesn't update the actual ball 2.
struct ball {
struct ball * adjacent;
size_t n_adjacent;
};
// Setting ball 2
struct ball ball2 = { .n_adjacent= 0, .adjacent = NULL } ;
// setting ball 1
struct ball ball1 = { .n_adjacent= 1, .adjacent = NULL } ;
// setting ball 1's adjacent
struct ball * ball1_adj = (struct ball*) calloc(1, sizeof(struct ball));
ball1_adj[0] = ball2;
ball1.adjacent = ball1_adj;
printf("Address of original ball 2 is: %p\n", &ball2);
printf("Address of ball 2 in the array is: %p\n", &(ball1.adjacent[0]));
// different but Ok as malloc has returned a pointer
ball1.adjacent[0].n_adjacent = 10; // Updating ball 2 's adjacents
printf("Adjacent of original ball 2 is: %d\n", ball2.n_adjacent); // prints 0
printf("Adjacent of ball 2 in the array is: %d\n", (ball1.adjacent[0]).n_adjacent); // prints 10
- Arent ball2 and ball1.adjacent[0] the same ball (ball2)?
- Why did not the value of the ball2 get updated?
Thanks
int main(void). Make sure it compiles and include the output in your question.[0]dereference a pointer, this dose not well tell what you are doing. Just use*(so if you havetype* varyou can derefercen it with*var)