0

I'm trying to write to memory using pointer as below, But it is writing to the unexpected address.

 uint32_t* pointer = (uint32_t) (__MEMORY_BASE)
 *(pointer+4)      = data;

While using the below its working as expected,

uint32_t* pointer = (uint32_t) (__MEMORY_BASE + 4)
*pointer      = data;

Can anyone please let me know, WHy I'm not able to use the first method to write to pointer address.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Learn about pointers and pointer arithmetics. `4` -> `1`. And use the ideomatic way to access hardware peripheral registers with the vendor-provided (CMSIS) headers. This code will not really work for other reasons, too. If this accesses RAM: don't do this! Use the linker and sections. – too honest for this site Jul 27 '17 at 10:56

4 Answers4

4

For any pointer p and index i, the expression *(p + i) is equal to p[i].

That means when you do

*(pointer + 4) = data;

you are actually doing

pointer[4] = data;

That means you write to the byte-offset 4 * sizeof(*pointer) from pointer. I.e. you write 16 bytes beyond __MEMORY_BASE.

To be correct either use the second variant, or use pointer[1] (or *(pointer + 1)) with the first variant.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0
uint32_t* pointer = (uint32_t) (__MEMORY_BASE);
 *(pointer+4)      = data;

because of pointer has type uint32_t *, this means that pointer + 1 = __MEMORY_BASE + 4, pointer + 4 = __MEMORY_BASE + 16, this is how pointer arithmetic works in C.

fghj
  • 8,898
  • 4
  • 28
  • 56
0

uint32_t is a integer type of 4 bytes. Pointer addition in C is in terms (and in multiples of) the pointed type size.

So pointer+4 adds 16 (4*4) to the pointer but in the second case you have an offset of 4 bytes.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

I think that you do not understand the pointer arithmetics

in the first one you add the pointed object (uint32_t) is 4 bytes long so is you add to the pointer 4 the actual address will be plus 4 * 4 bytes.

in the second example you add 4 to the actual address.

0___________
  • 60,014
  • 4
  • 34
  • 74