Home > Software design >  How to write an embedded C program for adding two numbers stored in memory locations
How to write an embedded C program for adding two numbers stored in memory locations

Time:11-27

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.

CodePudding user response:

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:

  • if these are device registers or shared memory that may change spontaneously outside of the current thread context, they should be declared volatile,
  • if the pointers should never change they should be declared const,
  • prefer initialisation over declare/assign,
  const volatile int* p = (const volatile int*)0x30610000 ;

It may be syntactically clearer to use a macro represent the value at the address such as:

#define p (*(volatile int*)0x30610000)
#define q (*(volatile int*)0x30610000)

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.

  • Related