Reputation: 48
Can use a pointer to access content of the memory location on embedded c.
int *p;
p = (int*) 0x30610000;
I need to write a program that add two numbers stored in memory location.
int *p;
int *q;
p = (int*) 0x30610000;
q = (int*) 0x30610004;
int sum=(*p)+(*q)
Is the above code correct?
I need understand how access a content of memory location on embedded c.
Upvotes: 3
Views: 1048
Reputation: 93476
You ask if it is "correct", then in comments ask whether it is "good practice". They are two separate questions. It is syntactically and semantically correct (apart from the missing semi-colon). Whether it is good practice is context dependent and to some extent a matter of opinion. You have provided little context to come to a view but consider:
volatile
, volatile int* const p = (volatile int* const)0x30610000u ;
It may be syntactically clearer to use a macro represent the value at the address such as:
#define p (*(volatile int*)0x30610000u)
#define q (*(volatile int*)0x30610000u)
int sum = p + q ;
But that may be regarded as an obfuscation. You would normally clarify such code by naming convention - macros at conventionally capitalised, and P
and Q
really don't cut it w.r.t. clarity or meaningfulness. The names should reflect the purpose or nature of the data stored
Where the values are hardware registers, the data type might explicitly match the register width, using stdint.h types.
Upvotes: 4
Reputation: 213832
The answer depends on how the values ended up in that memory location in the first place. There are 3 different scenarios:
In case the location is named with a variable name, you cannot access its absolute address like in your example. This can give all manner of problems related to optimization and pointer aliasing. In such cases you need to volatile
qualify all access to the variable, including the original declaration, and disable strict pointer aliasing as well (gcc -fno-strict-aliasing
). Such code is non-portable between compilers.
Otherwise, in case the location is not named, you can access it like you would with a hardware register. Follow the advise in the link above, including:
int
in embedded systems, always use the types from stdint.h
. Never use signed types in embedded systems unless the data is explicitly signed.u
/U
suffix all hex constants to avoid problems with signedness.volatile
qualify the access, for example by using a volatile uint32_t*
pointer.In your specific scenario also consider variable value ranges and over/underflow of values.
Upvotes: 2