c++ - 使用指针和偏移量遍历 stucts 成员的 vector 第 2 部分

标签 c++ pointers iteration pointer-arithmetic

这是我昨天提出并得到回答的问题的第 2 部分。所以今天我要带回第 2 部分。我不确定这是否应该在其他地方,所以如果版主想要移动它,请随意。

所以我不会在这里重新介绍我的问题,所以请阅读第 1 部分 Iterating through a vector of stucts's members with pointers and offsets

所以我想出了一个解决问题的方法,所以让我发布一个修改过的代码片段来代表我要寻求的解决方案,

#include <iostream>
#include <vector>

// knows nothing about foo
class Readfoo
{ 
    private:
    int offSetSize;
    char* pchar;

    public:
    void SetPoint(double* apstartDouble, int aoffSetSize)  
    {
        offSetSize = aoffSetSize;
        pchar = static_cast<char*> (static_cast<void*>(apstartDouble));
    };

    const double& printfoo(int aioffset) const
    {
       return *(static_cast<double*> (static_cast<void*>(pchar + aioffset*offSetSize)));
    };
};

// knows nothing about readFoo
struct foo
{ 
    int a[5];
    double b[10];
};

int main() 
{
    // populate some data (choose b [2] or other random entry.).
    std::vector<foo> bar(10);
    for(int ii = 0; ii < bar.size(); ii++) 
        bar[ii].b[2] = ii;

    // access b[2] for each foo using an offset.
    Readfoo newReadfoo;
    newReadfoo.SetPoint(&(bar[0].b[2]), sizeof(foo)/sizeof(char));
    for(int ii = 0; ii < bar.size(); ii++)
        std::cout<<"\n"<<newReadfoo.printfoo(ii);

    return 0; 
}

在我看来,这是合法的,我想这就是我要问的。从现在开始,本质上,我正在将我对结构 foo 和 vector bar(foo 数组)的“解释”转换为单个字节数组或字符数组。

即在这种解释中,数据结构是单个字符数组,foo 大小乘以 bar 大小。当我使用整数类型遍历它时,我实际上是在转向某个假设的 char 元素(第 1 部分的答案中的第 4.2 点)。然后 printfoo 函数将接下来的 8 个字节组合成一个 double 返回。

那么这是合法的吗?除了移出条形 vector 的边界之外还有什么原因导致它不起作用(我已经对其进行了测试,但尚未失败。)?

最佳答案

So is this legal ...

不,不是。

在下面的表达式中:

pchar + aioffset*offSetSize

你操作 pchar 就好像它是一个指向 char 数组的指针,但事实并非如此(它是一个指向 double 数组的指针).这是未定义的行为:

[expr.add]/6

For addition or subtraction, if the expressions P or Q have type “pointer to cv T”, where T and the array element type are not similar, the behavior is undefined. [ Note: In particular, a pointer to a base class cannot be used for pointer arithmetic when the array contains objects of a derived class type. — end note ]

在您的例子中,Ppchar 并且具有指向 char 的类型指针,但它指向的数组元素是 double.


... and other than moving out of bounds of the bar vectors is there any reason why this will not work (I have tested it and it has yet to fail.)?

是:Does the C++ standard allow for an uninitialized bool to crash a program?


更进一步:C++ 中的指针操作是一个危险信号。 C++ 指针操作是黑魔法,它会燃烧你的灵魂并吞噬你的狗。 C++ 提供了许多工具来编写通用代码。我的建议:询问您想要实现的目标,而不是询问您尝试的解决方案。你会学到很多东西。

关于c++ - 使用指针和偏移量遍历 stucts 成员的 vector 第 2 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54465924/

相关文章:

javascript - 在 localStorage 中存储有序对象/数组

c++ - 在 Vista/7 (C++) 上获取音量变化通知

c++ - 通过 X10 接收和解码曼彻斯特码

c++ - samplerCube 数组

C 函数指针错误

matlab - 确定 MATLAB fitglm() 模型拟合是否收敛

c++ - 在 OpenGL 中用一些颜色填充 Bresenham 圆

c - 如何明智地解释这个编译器警告?

arrays - 为什么 char** argv 与 char* argv[] 相同

tuples - 如何迭代 Julia NamedTuple 中的名称和值?