lynxx
lynxx

Reputation: 596

updating pointer in array doesn't update the original pointer

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

Upvotes: 0

Views: 164

Answers (1)

Gerhardh
Gerhardh

Reputation: 12404

Arent ball2 and ball1.adjacent[0] the same ball (ball2)?

No. You make a copy of ball2 and store it in ball1_adj[0] Then you assign the address of that copy to ball1.adjacent

Why did not the value of the ball2 get updated?

Because modifying a copy doesn't affect the source of that copy. Just as burning a photo of your car doesn't damage your car.

If you want to modify other structs using the adjacent pointer you need to assign the address of the other struct instead of a copy:

ball1.adjacent = ball1_adj;
=>  ball1.adjacent = &ball2;

Upvotes: 1

Related Questions