我正在编写一个类似于这段代码的单元测试,我试图在设置值时测试我的值,以便了解发生了什么。当我运行以下代码时,我不明白为什么指针值没有被设置为1。相反,当我运行它时,输出结果是10,64,0,0。
非常感谢您提供任何解释或建议!
非常感谢您提供任何解释或建议!
#include <stdio.h>
#include <stdbool.h>
typedef struct
{
bool bOne;
bool bTwo;
bool bThree;
bool bFour;
} items;
int main()
{
items item;
item.bOne = 0;
bool *ptr = &(item.bOne);
for(int i = 0; i < sizeof(items)/sizeof(bool); i++)
{
*ptr = 1;
*ptr++;
printf("ptr value = %d\n", *ptr);
}
return 0;
}
*ptr++;
会导致未定义的行为,因为它没有指向数组。它还会增加ptr
,之后指向未初始化的内存。因此,printf
输出的是垃圾数据。 - mch%d
,它期望一个int
,但你传递了一个bool
。尝试这样做:printf("ptr value = %d\n", (int)*ptr);
- Adrian