pointer

Hi,i am new to c++ and have gone through pointers.i have understood the following code up to where it says p1 = &firstvalue and p2 = &secondvalue.But i am a kind of stuck in the next line of code *p1 = 10 and *p2 = 20 because i don't know where those values come from.A help will be truly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  int first value =5,second value =15;
  int*p1,*p2;

  p1 = &first value;
  p2 = &second value;
  *p1 =10;
  *p2 =*p1
  p1 =p2;
  p1 = 20;
  cout <<"firstvalue is"<<firstvalue <<endl;
  cout <<"secondvalue is"<<secondvalue <<endl;
  return 0;


\
Last edited on
*p1 means "value stored in p1 address". p1 itself is an address (the address of 'first value'), so you have the address, and you're asking for what's inside that address. so, *p1 = 10; means "value stored in the p1 address is now 10".
same for p2.

just one more thing: variables can't have spaces in their names. so, i suggest changing "int first value" to "int first_value" or "int firstvalue". otherwise, you'll get errors.
Last edited on
oh! thanks for that correction
Topic archived. No new replies allowed.