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);
    ...
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3be23-2c2d7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3be23-2c2d7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?