*pt1++ givung wrong value

P

pxe

Hi,

Please let me know what is wrong with my code below. *pt1++ is giving
me 10.
Is it not valid?


#include<iostream>
#include<stdlib.h>


using namespace std;


int main(int argc,char *argv[])
{
int a=0;


int *pt1;
int *pt2;
float *pt3;


int values[100];


int *gels[100];


pt1=&a;
cout<<*pt1;
*pt1++;
a=*pt1;
cout<<a<<*pt1;


return 0;



}


Thanks and Regards
Babu
 
Z

Zara

Hi,

Please let me know what is wrong with my code below. *pt1++ is giving
me 10.
Is it not valid?

Its results are undefined, see comments below
#include<iostream>
#include<stdlib.h>


using namespace std;


int main(int argc,char *argv[])
{
int a=0;


int *pt1;
int *pt2;
float *pt3;


int values[100];


int *gels[100];


pt1=&a;
cout<<*pt1;
*pt1++;

This does nothing woth the value pointed by pt1 and increments the
pointer
A is assigned the value of undefined memory.
cout<<a<<*pt1;


return 0;



}


Best regards,

Zara
 
S

Salt_Peter

pxe said:
Hi,

Please let me know what is wrong with my code below. *pt1++ is giving
me 10.
Is it not valid?


#include<iostream>
#include<stdlib.h>


using namespace std;


int main(int argc,char *argv[])
{
int a=0;


int *pt1;
int *pt2;
float *pt3;


int values[100];


int *gels[100];


pt1=&a;
cout<<*pt1;
*pt1++;

translation: increment the pointer to integer so that pt1 points to pure
garbage.

load variable a with whatever garbage was found there.
cout<<a<<*pt1;

print the garbage twice.
 
J

Jim Langston

Comments inline. Code that doesn't apply snipped.

pxe said:
Hi,

Please let me know what is wrong with my code below. *pt1++ is giving
me 10.
Is it not valid?

#include<iostream>
#include<stdlib.h>

using namespace std;

int main(int argc,char *argv[])
{
int a=0;

int *pt1;

pt1=&a;

pt1 now points to the memory used to store the integer a.
cout<<*pt1;

You are displaying the contents of the memory used to store the integer a

You are incrementing the pointer. pt1 now points sizeof(int) bytes paste
the memory location used to store the integer a. Ooops. ++ takes precidence
over *. This means it evaluates to *(pt1++) incrementing the pointer then
taking the value, which nothing is done with. You need to manually set
precidence. Change this to (*pt1)++;

a now contains the contents of the memory sizeof(int) bytes past where a was
stored because of the above line.
cout<<a<<*pt1;

This should display the same (garbage) value twice.
 

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
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top