简体   繁体   English

如何在struct成员中给双指针赋值?

[英]How to assign value to the double pointer in struct member?

For some reason I want to assign value to the double pointer in struct member. 由于某种原因,我想为struct成员中的double指针赋值。 I have structure that have 3 member's first is int, second is pointer to that int, and third is double pointer, which point to second member (to pointer). 我有3个成员的结构,第一个是int,第二个是指向该int的指针,第三个是双指针,它指向第二个成员(指向指针)。 That third member don't know how to define as well. 第三位成员也不知道如何定义。 Here is source: 这是来源:

#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;
}

OS: win 7, 64, c++ (c++ Builder 2010) 操作系统:Win 7,64,C ++(C ++ Builder 2010)

Try this: 尝试这个:

st2->c = &st2->b;

Assigning a pointer-to-pointer is exactly the same as assigning a pointer-to-int. 分配指针到指针与分配指针到int完全相同。 You simply give it the address of a pointer, rather than the address of an int. 您只需为其提供指针的地址,而不是int的地址。

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

st mySt;

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

With the last assignment, you get the address of field b , which is a pointer, so it is the address of a pointer, then field c is correctly initialized as a pointer to a pointer. 在最后一次赋值后,您将获得字段b的地址(即指针),因此它是指针的地址,然后正确地将字段c初始化为指向指针的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM