Segmentation Fault in strcpy()

后端 未结 3 782
耶瑟儿~
耶瑟儿~ 2020-11-30 14:29

I have a basic structure like this

typedef struct struck {
    char* id;
    char* mat;
    int value;
    char* place;
} *Truck;

And afunc

3条回答
  •  一向
    一向 (楼主)
    2020-11-30 15:31

    Your typedef defines Truck as a struct struck *, i.e. a pointer. So it's size will be 4 or 8 depending on the architecture and not the size of the struct

    Use sizeof(*Truck) to get the actual size of the struct.

    You also need to allocate memory for the characters. The easiest way would be using strdup().

    Truck CTruck(const char* id, const char* mat, int value, const char* place) {
        Truck nT = malloc(sizeof (*Truck));
        nT->value = value;
        nT->id = strdup(id);
        nT->mat = strdup(mat);
        nT->place = strdup(place);
        return nT;
    }
    

    However, I would suggest changing your typedef so it's an alias for the struct, not for a pointer to it:

    typedef struct {
        char* id;
        char* mat;
        int value;
        char* place;
    } Truck;
    

    In your function you then use this:

    Truck *nT = malloc(sizeof(Truck));
    

提交回复
热议问题