首页 > 解决方案 > 有没有更好的方法来迭代指针而不将其重新分配给不同的变量?

问题描述

struct hello1 {
    int64_t world1;
    int64_t world2;
    int64_t world3;
    int64_t world4;
    int64_t world5;
}

void something (struct hello1 *first) {

    int64_t *foo1 = &first->world1;

    for (int64_t i = 0; i < 0x30; i++) {
        printf("Address: 0xllx", foo1);
        foo1++;
    }
}

我目前正在将地址 , 分配&first->wordl1给 *foo1。

有没有更好的方法来增加结构中的下一个指针而不创建int64_t *foo1

标签: c

解决方案


尝试struct通过指针算术从任何其他成员访问 的任何成员的行为是未定义的。

更详细地说,C 标准允许您读取指针值&world1(并取消引用它)和指针值&world1 + 1(但延迟它)。但它不允许您读取指针值&world1 + 2及以上。

考虑使用数组int64_t代替。然后指针算术将是有效的,并且您不需要那些额外的演员表。

如果您坚持hello1原样并希望能够通过索引访问成员,请考虑

inline int64_t* getHello1Element(struct hello1* h, size_t i)
{
    switch (i){
    case 0:
        return &h->world1;
    case 1:
        return &h->world2;
    case 2:
        return &h->world3;
    case 3:
        return &h->world4;
    case 4:
        return &h->world5;
    }
}

这将是 O(1) 与一个好的编译器。


推荐阅读