getting the variable from its adress.

This is a discussion on getting the variable from its adress. within the C++ Programming forums, part of the General Programming Boards category; Well, I am kind of new at programing and I have a question: Now I am given the address of ...

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    1

    getting the variable from its adress.

    Well,
    I am kind of new at programing and I have a question:

    Now I am given the address of a variable.
    Lets say the address is "0x0955e100".
    I also know what is stored in that adress.
    Lets say an integer.
    But I do not know the name of the variable.
    Lets call it variable X.
    Now I define a variable, lets say:
    int MyVar;

    What I want is to assign variable at the adress 0x0955e100 to MyVar.

    But I cannot directly say MyVar = X; because I dont know the name (X is just a name I give because I dont know what in fact it is called).
    I just know the adress.

    How can I do it?
    Please help.

  2. #2
    Registered User
    Join Date
    Jun 2008
    Posts
    54
    Code:
    #include <stdio.h>
    
    const int var = 5;
    
    int main()
    {
    	int MyVar = *((int*)0x4020a0);
    	printf("%d\n", MyVar); /* This prints "5" on my computer */
    	return 0;
    }
    On my system and for this program, the virtual address of "var" happened to be 0x4020a0 when I ran it.

    What I've done here is cast that address to an int pointer, and then dereference it to store in MyVar.

    You really don't want to write programs this way, though, because the system you are trying to program for probably uses virtual memory. This means that each program on your computer runs in its own address space, making the address numbers it uses meaningful only to itself and the system which translates them back to physical addresses. Even if programs you write like this somehow work, they will not be portable (you won't be able to share them).
    Last edited by Boxknife; 02-04-2011 at 09:11 AM.

  3. #3
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    1,625
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Realloc problem, environment variables Linux C
    By yodakohl in forum C Programming
    Replies: 4
    Last Post: 01-05-2011, 06:04 PM
  2. Pointers
    By MrMatt027 in forum C++ Programming
    Replies: 14
    Last Post: 12-10-2010, 03:32 PM
  3. Question about printing a variable???
    By Hoser83 in forum C++ Programming
    Replies: 2
    Last Post: 03-31-2006, 12:57 PM
  4. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 11:07 AM
  5. Replies: 2
    Last Post: 04-12-2004, 01:37 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21