pointer problem

i have a program here. it is currently working the only problem is it gives the wrong answer


#include <cstdlib>
#include <iostream>
#include <stdio.h>

using namespace std;
int main()
{

int intarr[4] = {1,2,3,4 };
int i;
int *ptr;
ptr=intarr;

for(i=0; i<4; i++)
{
printf("element %d value = %d \n", i, *ptr);
ptr++;
cout<<ptr<<endl;

}


int adress;
printf("Please Enter an Address");
scanf("%X", &adress);

ptr = (int*)adress;

printf("The Value of %X is %d", adress, *ptr);


system("PAUSE");
return EXIT_SUCCESS;
}

The address that the program shows me is wrong how do i fix this

i used this
http://cplusplus.com/forum/beginner/1777/
as my source
1
2
3
4
5
6
7
8
#include<stdio.h>
int main()
{
   int* ptr=(int*)0x22FF74;
   printf("%d",*ptr);

   return 0;
}

was the code that printed the value in the address, but to print the address of a variable(in this case a pointer) you need to print out the reference (aka the "address of") operator &

1
2
3
4
5
6
7
8
9
10
#include<stdio.h>
int main()
{
   int* ptr=(int*)0x22FF74;
   printf("%d\n",*ptr);

   printf("0x%X\n", &ptr);

   return 0;
}


so just change: printf("The Value of %X is %d", adress, *ptr);
to this: printf("The Value of %X is %d", &adress, *ptr);

and to nitpick, address is spelled with 2 d's, and instead of using system calls you should try and find better standard workarounds, such as cin.ignore(1000,'\n');

EXIT_SUCCESS could be better replaced with a 0; less typing anyway.
Last edited on
here is the output of my program:

element 0 value = 1
0x22ff64
element 1 value = 2
0x22ff68
element of 2 value = 3 0x22ff6c
element 3 value = 4
0x22ff70

Please Enter an Address 0x22ff6c
The Value of 22ff54 is4


I am expecting my program to answer 3


and when i asked 0x22ff64 my program should answer 1

currently my computer just answer random values
"it is currently working the only problem is it gives the wrong answer"

Ya gotta love it!
Only in Computer Science and Politics can you get away with a phrase like that.
can you show the revised code, and please use code tags.
Last edited on
Topic archived. No new replies allowed.