gpt4 book ai didi

c - 指针调用的结构成员分配了不同的值

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:57 25 4
gpt4 key购买 nike

我有以下一段 C 代码,它显示了一个奇怪的结果。S_data 是一种结构数据类型。谁能帮我知道这是什么原因

int i;

typedef struct
{
uint8_t D[19];
uint32_t *D_ptr[19];

} sys_data;

代码:

for (i = 0; i < 20; i++) {
S_data.D[i] = 0;
console("%d",S_data.D[i]);
S_data.D_ptr[i] = &S_data.D[i];
}

for ( i = 0; i <20; i++) {
console("Value of var[%d] = %d\n", i, *S_data.D_ptr[i] );
console("Address of var[%d] = %u\n", i, S_data.D_ptr[i] );
}

输出:

Address of var[0] = 536872044
Value of var[1] = 0
Address of var[1] = 536872045
Value of var[2] = 0
Address of var[2] = 536872046
Value of var[3] = 0
Address of var[3] = 536872047
Value of var[4] = 0
Address of var[4] = 536872048
Value of var[5] = 0
Address of var[5] = 536872049
Value of var[6] = 0
Address of var[6] = 536872050
Value of var[7] = 0
Address of var[7] = 536872051
Value of var[8] = 0
Address of var[8] = 536872052
Value of var[9] = 0
Address of var[9] = 536872053
Value of var[10] = 0
Address of var[10] = 536872054
Value of var[11] = 0
Address of var[11] = 536872055
Value of var[12] = 0
Address of var[12] = 536872056
Value of var[13] = 0
Address of var[13] = 536872057
Value of var[14] = 0
Address of var[14] = 536872058
Value of var[15] = 0
Address of var[15] = 536872059
Value of var[16] = 0
Address of var[16] = 536872060
Value of var[17] = 1811939328
Address of var[17] = 536872061
Value of var[18] = 74186752
Address of var[18] = 536872062
Value of var[19] = 289792
Address of var[19] = 536872063

此处 var[17] 应为 0,但显示不同的值。但是如果我不使用指针直接打印 var[17] 值,我会得到正确的结果。

最佳答案

您违反了严格的别名规则。(S_data.D_ptr[i] = &S_data.D[i];) 所以这是未定义的行为。您不能像这样将一种类型的指针分配给另一种类型。

typedef struct
{
uint8_t D[19];
uint8_t *D_ptr[19];

} sys_data;

这为您解决了问题。

同时打印 uint32_t 使用(如果您将其声明为 uint32_t)。

printf("%" PRIu32 "\n", *S_data.D_ptr[i]);

也像这样打印指针

printf("%p", (void*)S_data.D_ptr[i]);

关于c - 指针调用的结构成员分配了不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48223093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com