c++ - 如何给struct成员中的双指针赋值?

标签 c++ pointers struct double

出于某种原因,我想为结构成员中的双指针赋值。我的结构有 3 个成员,第一个是 int,第二个是指向该 int 的指针,第三个是双指针,指向第二个成员(指向指针)。第三个成员也不知道如何定义。这是来源:

#include <iostream.h>

typedef struct {
    int a;
    int *b;
    int **c;
} st;

st st1, *st2 = &st1;

void main(){
// first define a member  
    st1.a = 200;
// second assign b pointer member to a
    st2->b = &st1.a;
// third assign c pointer member to b (but that don't work)
    *(st2)->c = st2->b;
}

操作系统:win 7、64、c++ (c++ Builder 2010)

最佳答案

typedef struct {
    int a;
    int *b;
    int **c;
} st;

st mySt;

void main() {
    mySt.a = 200;
    mySt.b = &mySt.a;
    mySt.c = &mySt.b;
}

最后一次赋值,得到字段b的地址,它是一个指针,所以是指针的地址,那么字段c就正确初始化了作为指向指针的指针。

关于c++ - 如何给struct成员中的双指针赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8467469/

相关文章:

C:使用大量结构会使程序变慢吗?

c++ - 防止 gcc 在包含搜索路径上搜索当前目录 "-I-"选项

c++ - GMP:将整数转换为 std::string

c++ - OpenGL 链接器错误,链接未编译的着色器

c++ - (->) 箭头运算符和 (.) 点运算符,类指针

c - 参数中的数组没有变量初始化

c - 将 strstr() 函数与指针一起使用

c - 如何在使用结构指针时实现 gets() 或 fgets()?

c++ - Sql Like在c++中的类似用法

c - 使用 malloc 分配结构数组