Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a value from a memory adress in C? [duplicate]

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?

like image 902
Joe Carr Avatar asked Oct 16 '25 17:10

Joe Carr


2 Answers

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 )
like image 144
Lundin Avatar answered Oct 19 '25 07:10

Lundin


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)
like image 45
eerorika Avatar answered Oct 19 '25 07:10

eerorika