The problem of structure initialization in C language

// C
typedef struct {
    ElemSet e1;
    ElemSet e2;
    ElemSet e3;
}Triplet;

// 
Status InitTriplet(Triplet *t,ElemSet v1,ElemSet v2,ElemSet v3) {
    // 
    t = (Triplet *)malloc(sizeof(Triplet));
    if (!t) {
        // 
        return ERROR;
    }
    
    t->e1 = v1;
    t->e2 = v2;
    t->e3 = v3;
    return OK;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    Triplet t;
    InitTriplet(&t, 10, 15, 20);
    printf("%p\n", &t);
    printf("%d\n", t.e2);
    t.e2 = 100;
    printf("%d\n", t.e2);
    return 0;
}

Why do I initialize it through the InitTriplet method and then get a value of 0 for e2 instead of the 15 I passed in?

C
Sep.18,2021

it's a mess.

first of all, the InitTriplet function doesn't work, because t is just a local variable. It has to be declared as Triplet * * . That's why your initialization doesn't work. Secondly, in the main function, t is already an automatic variable (memory has been automatically allocated on the stack). What is the purpose of applying for space for it?

I guess your purpose should be like this:

Status InitTriplet(Triplet **t, ...);

int main(int argc, const char * argv[]) {
    Triplet *t = 0;
    InitTriplet(&t, 10, 15, 20);
    ...
}
Menu