0

Can somebody please explain this code

// Option 1
int **p = new Point*[2];
p[1] = new Point;
p[1]->x = p[1]->x = 1;

// Option 2
int **p = new Point*[2];
*(p+1) = new Point;
(*(p+1))->x = (*(p+1))->x = 1;

Isn't both options the same? Why when I create the variable using option 2, I cant write its value with option 1 (I got random numbers (address numbers?))? Is there any difference?

7
  • 10
    Yes, there's a difference; the second example never initialises y. Commented Apr 24, 2012 at 18:45
  • 2
    Well, for one thing you don't assign y to anything in Option 2 -- you do ->x twice. Commented Apr 24, 2012 at 18:46
  • 1
    Oh, I see you edited your example now so that both options have the same error. Commented Apr 24, 2012 at 19:20
  • The pseudo-code you have provided doesn't demonstrate the problem. Please create the smallest actual program that does demonstrate the problem and paste that program, in its entirety, into your question. See sscce.org. (Hint: you should be able to demonstrate the problem in 10 lines or so.) Commented Apr 24, 2012 at 19:22
  • @Robᵩ the OP "demonstrates" the problem in the comment to CodeChordsman's answer below, by using some UB in printf. Commented Apr 24, 2012 at 19:25

1 Answer 1

1

You have a typo: (*(p+1))->x = (*(p+1))->x = 1; - should be y in the second term

Sign up to request clarification or add additional context in comments.

2 Comments

sorry, there should by "x" as you have written. Im writing a project and I got different outputs on printf("%f != %f", p[1], *(p+1));
@Buksy Why are you using %f there? %f expects a double, not a pointer to a struct. Of course it prints two different values!

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.