Writing to memory using pointer

2.8k Views Asked by At

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.

4

There are 4 best solutions below

1
fghj On
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.

0
Basile Starynkevitch On

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.

0
Some programmer dude On

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.

0
0___________ On

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.