【问题标题】:Constant pointer to a constant structure is zero指向常量结构的常量指针为零
【发布时间】:2020-04-21 11:55:56
【问题描述】:

我正在处理其他人开发的一段代码,并且我正在尝试使结构静态化。但是在调试时,指针似乎为零(不是指向零的变量):

typedef struct WiFiIP{
    // Keep the following in order!  (pri,sec)
    uint16_t WiFiPrimaryPort;
    uint16_t WiFiSecondaryPort;
    // Keep the following in order!  (pri,sec,sntp)
    char WiFiPrimaryAddress[32];
    char WiFiSecondaryIpAddress[32];
    char WiFiSntpIpAddress[32];
};
static const struct WiFiIP WiFiIPs = {7781,7781,"10.0.0.1","",""};
static const __typeof__ (WiFiIPs.WiFiPrimaryPort)
        * const PortPtr = &WiFiIPs.WiFiPrimaryPort;

static const __typeof__(WiFiIPs.WiFiPrimaryAddress)
    *AddressPtr = &WiFiIPs.WiFiPrimaryAddress;

所以AddressPtrPortPtr 都是0x0

我知道还有许多其他方法可以在代码中“硬编码”参数,但在这种情况下,现有代码需要一个指向结构的指针,我想避免重构。

请温柔一点,我从来不擅长指针,而且我知道有很多关于指针的文献。我已经搜索并遵循了许多示例,但无法使其正常工作。

此代码正在为 cortex-m3 处理器开发

【问题讨论】:

  • 这两个变量都应该是非空的。可能还有其他事情发生。请使用minimal reproducible example 更新您的问题,以证明问题。
  • "所以 AddressPtr 和 PortPtr 都是 0x0。"没有,你用什么调试器?
  • 我讨厌那种强迫每个 C 学生在喉咙里写上typedef 的教育系统,即使它什么也没做。
  • 优化器不是可能内联常量吗?那么指针为空就有意义了。
  • @LouisCloete 你是对的,当我按照代码进行操作时,似乎指针正在被优化为内联。所以这个问题是一个红鲱鱼。

标签: c pointers struct constants cortex-m3


【解决方案1】:

这不应该发生,如果我复制您的确切代码,它似乎对我来说按预期工作。不幸的是,您没有包括 如何显示指针值。

要正确打印指针的值,您可以使用以下内容:

printf("PortPtr points to memory location at: %#lX\n", (uintptr_t)PortPtr);
printf("AddressPtr points to memory location at: %#lX\n", (uintptr_t)AddressPtr);

在这种情况下,您应该能够验证指针未初始化为 NULL。

【讨论】:

  • 感谢并抱歉没有在我的原始帖子中说我正在研究 cortex-m3,我已经更新了帖子。
  • 我看不出这有什么关系,只要你有 printf 或等效的,这段代码应该可以正常工作。我也可以在 Cortex-M4 上运行它...
猜你喜欢
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 1970-01-01
  • 2014-02-23
  • 2016-12-30
  • 2020-03-25
  • 1970-01-01
  • 2013-01-04
相关资源
最近更新 更多