首页 > 解决方案 > 指向常量结构的常量指针为零

问题描述

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

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 处理器开发

标签: cpointersstructconstantscortex-m3

解决方案


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

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

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。


推荐阅读