John Smith
John Smith

Reputation: 483

Cannot update pointer value

I may have a fundamental misunderstanding about how pointers work, but I thought I could assign a variable value to a pointer, however whenever I print the dereferenced value of the pointer it is always 0 rather than the value of 'timestamp'.

volatile uint32_t *myAddress = (volatile uint32_t*)0x12341234;

uint32_t timestamp = 0x1111;

*myAddress = timestamp;

Upvotes: 0

Views: 150

Answers (2)

0___________
0___________

Reputation: 67476

volatile uint32_t *myAddress = (volatile uint32_t*)0x12341234;

this kind of fixed address pointers are in common use in the uC development to access the memory mapped hardware registers or the memory at the exact address.

for example:

(ARM STM32)

volatile uint32_t *initialSP = (volatile uint32_t *)(0x8000000);

#define GPIOA               ((GPIO_TypeDef *) GPIOA_BASE)
GPIOA -> MODER = value;

The address has to have the physical sense - ie it has to be valid.

Your probably is not and you get the hardware or memory fault.

Upvotes: 0

bruno
bruno

Reputation: 32586

Cannot update pointer value

You mean cannot update pointed value

Doing

 volatile uint32_t *myAddress = (volatile uint32_t*)0x12341234;

 uint32_t timestamp = 0x1111;

 *myAddress = timestamp;

you use the (very probably) invalid address 0x12341234, to deference it has an undefined behavior

Do something like that :

uint32_t v;

volatile uint32_t *myAddress = &v;

uint32_t timestamp = 0x1111;

*myAddress = timestamp;
// now v values 0x1111

Example :

#include <stdio.h>
#include <stdint.h>

int main()
{
  uint32_t v = 0;

  volatile uint32_t *myAddress = &v;

  uint32_t timestamp = 0x1111;

  *myAddress = timestamp; // now v values 0x1111

  printf("0x%x 0x%x\n", (unsigned) v, (unsigned) *myAddress);

  return 0;
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
0x1111 0x1111
pi@raspberrypi:/tmp $ 

Upvotes: 4

Related Questions