POINTER

I am writing simple code of pointer. But i m comfused here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
using namespace std;

int main()
{
    int i = 5;
    int *ip1 = &i;
    int *ip2;
    ip2 = &i;

    cout << *ip1 <<endl;
    cout << *ip2 << endl;
}



In above code 1st I assigned "*ip1 = &i" and after that "ip2 = &i".
when i print *ip1 and *ip2 then they both print same values.
I m confused here. Assigning ADDRESS to *ptr1 & ADDRESS to ptr2 doesnt make any difference while printing both.





That is because they both point to the same value. ip1 is a pointer to i, and so is ip2. You'd notice that if you changed the value of i later, then both ip1 and ip2 would print a value relevant to i. This is just the way pointers work.
Thanks for reply.... but here another query is that..

1
2
3
4
5

 int i = 5;
 int *ip1 = &i;




Above code run OK. And Output is 5.

but

1
2
3
4
5
6
 

int i = 5;
int *ip1;  
*ip1 = &i;



This code shows error "invalid conversion from '"int*"' to 'int'
I did slide change in code but not working.
Last edited on
Thanks for giving me link which almost solve my problem.
In case of line 5 the * is the deference operator which enables you to change the content of the variable and not the pointer.

change line 5 to : ip1 = &i;
Its because you are dereferencing ip1 when you are assigning it to the address of i. The error is saying it cannot change from a pointer address (&i) to a plain integer (the value pointed to by ip1). Instead, you probably want to do this:
1
2
3
int i = 5;
int *ip1;
ip1 = &i;

Then, if you want to set the value pointed to by ip1, you dereference it first, like this:
 
*ip1 = 6;


It would probably be worth your while to find a few tutorials on pointers and read them a few times (sometimes it helps to get a different look at things).
ok now I understand... Thanks to all of you... :)
Topic archived. No new replies allowed.