遍历c中的结构 [英] iterating through a struct in c

查看:70
本文介绍了遍历c中的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写类似于此代码的单元测试,并且在设置值时尝试测试我的值,以便我知道发生了什么.当我运行以下代码时,我不明白为什么ptr值未设置为1.相反,当我运行它时,它的输出为10、64、0、0.

I am writing a Unit Test that is similar to this code, and I am trying to test my values as I set them, so that I know what is going on. I don't understand why the ptr values are not being set to 1, when I run the following code. Instead when I run this it gives me an output of 10, 64, 0, 0.

任何解释或建议将不胜感激!

Any explanation or advise would be greatly appreciated!

#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++中,++的优先级高于*,因此此后递增指针,并读取和丢弃原始值指向.现在指针已递增,您正在读取printf中的未初始化内存.如果您打算增加所指向的值,请尝试:

In *ptr++, the ++ has higher precedence than the *, so this post-increments the pointer, and reads and discards the value originally pointed to. Now that the pointer has been incremented, you are reading uninitialized memory in the printf. If your intention was to increment the value being pointed at, try:

(*ptr)++;

ptr[0]++;

编辑

嗯,由于您的循环绑定是基于适合结构体大小的bool的数量,所以您的意图可能是增加指针.在这种情况下,您不需要同时取消引用它,并且您不应该期望在printf中获得任何有意义的东西.另外,如前所述,由于该结构不是数组,由于编译器可能决定添加填充,因此您将进入未定义的行为域:

Hmm, since your loop bound is based upon the number of bools that fit in the size of the struct, maybe your intention was to increment the pointer. In which case, you don't need to dereference it at the same time, and you shouldn't expect to get anything meaningful in the printf. Also, as pointed out, since the struct is not an array, you will be wandering into undefined behavior land since the compiler may decide to add padding:

根据C99§6.7.2.1:

From C99 §6.7.2.1:

12结构或联合对象的每个非位字段成员都以适合于其类型的实现定义的方式对齐.

12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.

13在结构对象中,非位字段成员和位字段所在的单元的地址按照声明的顺序增加.指向经过适当转换的结构对象的指针指向其初始成员(或者,如果该成员是位字段,则指向它所驻留的单元),反之亦然.结构对象中可能有未命名的填充,但在其开头没有.

13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

这篇关于遍历c中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆