3

A bit of a silly question but here it is - how do I get a value based on its address?

Usually to get the address for a certain value I just print it out like this:

printf("%p", &loc);

But now I need to get a value based on its address in memory. How do I do that?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Joe Carr
  • 445
  • 1
  • 10
  • 23
  • 1
    That would depend on what is the effective type of `loc`. C *is* a statically typed language... – StoryTeller - Unslander Monica Mar 15 '17 at 07:50
  • loc can be put as #define loc 0x100 – Joe Carr Mar 15 '17 at 07:51
  • If you have the address of a value, then you have a pointer. You should use the dereference operator to dereference the pointer an you get the value. The type of the pointer must match the data type you want to read. – harper Mar 15 '17 at 07:52
  • 1
    Then your entire code is ill-formed. You can't take the address of a constant – StoryTeller - Unslander Monica Mar 15 '17 at 07:52
  • 1
    Where did you get `loc` from? You might be looking to set a volatile pointer to it, but that’s a bit rare. See https://stackoverflow.com/questions/2389251/pointer-to-a-specific-fixed-address if that’s really the case. – Ry- Mar 15 '17 at 07:53

4 Answers4

3

The addressof operator returns an object that is a pointer type. The value of the pointer is the memory address of the pointed object (which is loc). You can get the value of the object at the pointed memory address by dereferencing the pointer with the dereference operator:

*(&loc)
eerorika
  • 232,697
  • 12
  • 197
  • 326
3

The standard way of accessing a particular address 0x12345678 (such as a hardware register) is:

(volatile uint32_t*)0x12345678

If you want to use the contents of that address as if it was a variable, you could either have a pointer point there, or make a macro:

#define REGISTER ( *(volatile uint32_t*)0x12345678 )
Lundin
  • 195,001
  • 40
  • 254
  • 396
1

An address has no type, but assuming you know it, you may use the follow line:

printf("%d", *(int*)p);

You could test several types to check what is in there:

printf("%d", *(int*)p);
printf("%f", *(float*)p);
...

Be careful, that the address is required to belong to the current process, if not, the memory protection will kill your process.

Adrian Maire
  • 14,354
  • 9
  • 45
  • 85
1

you can simply use the asterisk to get the value of the variable the pointer is pointing to.

type x = *loc

i used type because i don't know the type of loc(it may be int, double, float,...)

Fatemeh Karimi
  • 914
  • 2
  • 16
  • 23