首页 > 解决方案 > 无法更新指针值

问题描述

我可能对指针的工作方式有一个基本的误解,但我认为我可以为指针分配一个变量值,但是每当我打印指针的取消引用值时,它总是 0 而不是“时间戳”的值。

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

uint32_t timestamp = 0x1111;

*myAddress = timestamp;

标签: c

解决方案


无法更新指针值

你的意思是不能更新指向值

正在做

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

 uint32_t timestamp = 0x1111;

 *myAddress = timestamp;

您使用(很可能)无效地址0x12341234,以尊重它具有未定义的行为

做这样的事情:

uint32_t v;

volatile uint32_t *myAddress = &v;

uint32_t timestamp = 0x1111;

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

例子 :

#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;
}

编译和执行:

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

推荐阅读