简体   繁体   中英

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. 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). 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)

Try this:

st2->c = &st2->b;

Assigning a pointer-to-pointer is exactly the same as assigning a pointer-to-int. You simply give it the address of a pointer, rather than the address of an 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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