how pointers behave with int and arrays

R

rahul8143

hello,
Consider following code1
int main()
{
int i=100;
int &k=i;
k++;
cout<<i<<endl;
int *p=&i;
(*p)++;
cout<<*p<<endl;
i++;
cout<<i<<endl;
RETURN 0;
}
Now to incremanet i value i have to use (*p)++ instead of *p++.

now consider code2
int main()
{
int a[]={11,22,33,44};
int *p=a;
cout<<++*p++<<endl; //12
cout<<(*p)++<<endl; //22
return 0;
}
why in above code why (*p)++ gives 22 instead 23? Also how
++*p++ gets evaluated?
regards,
rahul.
 
K

Karl Heinz Buchegger

now consider code2
int main()
{
int a[]={11,22,33,44};
int *p=a;
cout<<++*p++<<endl; //12
cout<<(*p)++<<endl; //22
return 0;
}
why in above code why (*p)++ gives 22 instead 23?

because the result of i++ is the value of i *before* the increment
happend.
Also how
++*p++ gets evaluated?

++( ( *( p ++ ) )
 
C

Christian Meier

hello,
Consider following code1
int main()
{
int i=100;
int &k=i;
k++;
cout<<i<<endl;
int *p=&i;
(*p)++;
cout<<*p<<endl;
i++;
cout<<i<<endl;
RETURN 0;
}
Now to incremanet i value i have to use (*p)++ instead of *p++.

now consider code2
int main()
{
int a[]={11,22,33,44};
int *p=a;
cout<<++*p++<<endl; //12

You are incrementing your pointer here. p points now to a[1] and no more to
a[0]. The second element of a is changed from now on.
cout<<(*p)++<<endl; //22
return 0;
}
why in above code why (*p)++ gives 22 instead 23? Also how
++*p++ gets evaluated?

Is answered in another post.
regards,
rahul.

Greetings Chris
 
G

Gianni Mariani

hello,
Consider following code1
int main()
{
int i=100;
int &k=i;
k++;
cout<<i<<endl;
int *p=&i;
(*p)++;
cout<<*p<<endl;
i++;
cout<<i<<endl;
RETURN 0;
}
Now to incremanet i value i have to use (*p)++ instead of *p++.

now consider code2
int main()
{
int a[]={11,22,33,44};
int *p=a;
cout<<++*p++<<endl; //12
cout<<(*p)++<<endl; //22
return 0;
}



int main()
{
int a[]={11,22,33,44};
int *p=a;

int * tmpp = p;

p= 1 + p;

* tmpp = 1 + * tmpp;

int tmppp = * tmpp;

cout << tmppp << endl; //12

int tmpppp = *p;

*p = 1 + *p;

cout << tmpppp << endl; //22
return 0;
}

why in above code why (*p)++ gives 22 instead 23? Also how
++*p++ gets evaluated?

1. The p++ first
2. The *p (on the previous version of p (which is a[0]))
3. The ++(a[0]).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top