0

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

2
  • Please provide a minimal reproducible example, which includes the struct definitions and a definition of int main(void). Make sure it compiles and include the output in your question. Commented Apr 6, 2020 at 16:36
  • 1
    Do not use [0] dereference a pointer, this dose not well tell what you are doing. Just use * (so if you have type* var you can derefercen it with *var) Commented Apr 6, 2020 at 16:40

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

How would I assign 3 balls?
With the given structure you cannot. You would need to replace the pointer with a an array of pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.