从指针结构

时间:2017-10-05 02:20:11

标签: c function pointers struct

我有一个像这样的结构

typedef struct Thing{
    int att;
} Thing;

Thing *newThing(){
    Thing *t;
    t = (Thing *)(malloc(sizeof(Thing)));
    thing->att = 0;
    return t;
}

我有一个printThing函数,试图像这样在att中打印值:

void printThing(Thing *t){
    printf("%d", t->att);
}

然而,这会导致分段错误,但我可以以相同的方式打印正确的值。我做错了什么?

int main(){
    Thing *t1 = readThing();//This works
    printf("%d", t1->att); //This also works
    printThing(t1); //Segmentation fault

    return 0;
}

1 个答案:

答案 0 :(得分:1)

问题可能在这里:

Thing *newThing(){
    Thing *t;
    t = (Thing *)(malloc(sizeof(Thing)));
    thing->att = 0;
    return t;
}

因为你动态分配内存并使t指向它,但是你应该thing->att = 0;而不是t->att = 0;