【问题标题】:Struct with Pointers in C++C++ 中带指针的结构体
【发布时间】:2026-01-24 05:00:01
【问题描述】:

我的数据结构还没有被复习,我在使用结构时遇到了问题。

我想创建一个结构,该结构将指向我从输入文件中获取的数组中的值。

比如说我在这里创建了一个结构:

struct complexnums {
    float * real;  //A ptr to real list
    float * imag;  //A ptr to imag list
};

int main()
{
    //Lets say this is an array I have taken from file input
    float real [] = {1.0, 2.0, 3.0, 4.0};
    float imag [] = {0.5, 1.0, 1.5, 2.0};

    //How can I assign the structure ptr's to these arrays?
    //Do I do it like this?
    complexnums complex = {&real[0],&imag[0]};
}

给出的例子,上面是给它赋值的正确方法吗? struct 是否真的会获得指向上面这些值的指针?

我也在看一个结构体的样例,这个人就是这么做的。

typedef struct {
    int sample;
    int *test1;
}
struct1, *struct2;

struct1struct2 有什么区别?

抱歉,如果这可以理解,请告诉我。如果没有,我会尽力编辑它。

【问题讨论】:

  • 你有理由使用 C 风格的数组吗?有理由使用原始指针吗?
  • @PierreAntoineGuillaume 有理由不这样做吗?
  • 另外,这类问题很难回答,因为你实际上在 1 中嵌入了 3/4 个问题。
  • @vandench 我想是的。我认为处理引用和 stl 对象可以更好地学习 c++。内存泄漏绝对是许多程序中的一个问题,因为它是一个复杂的问题,与错误处理等难以理解的问题有关。所以我建议使用 std::vectors 和智能指针。
  • 您的编辑刚刚打破了您的问题。在那之前还好。我正要评论说是的:它(过去)很好,除了过于复杂,因为你可以只使用= { real, imag },因为数组类型被省略为指针。

标签: c++ data-structures struct


【解决方案1】:

要回答您问题的第二部分,请在声明中:

typedef struct myStruct {
    //...
} structType, *ptrToStructType;

生成的类型定义为structType,是struct myStruct 的简写,ptrToStructTypestructType* 的简写。结构标识符是可选的(在本例中为myStruct,在您的中省略)。

见: Confusion with typedef and pointers in C

【讨论】:

    【解决方案2】:

    要回答第一个问题,是的,您可以以这种方式分配指针并且是正确的。但是任何审查代码的人都可能会感到困惑。因此重命名成员和变量会更清晰。

    在通过首先定义复数然后分配单个成员来分配复数时,很明显不要混合,因为直接初始化很容易将实数分配给虚数,反之亦然。

    struct complexnums {
        float * reals;  // A ptr to array of reals
        float * imags;  // A ptr to array of imaginarys
    };
    
    int main()
    {
        float realArray [] = {1.0, 2.0, 3.0, 4.0};
        float imagArray [] = {0.5, 1.0, 1.5, 2.0};
    
        complexnums complex;
        complex.reals = realArray;
        complex.imags = imagArray;
    }
    

    【讨论】: