Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a char pointer in a struct

I have defined a "car" struct with a model (char *model) and the year of the model (int year). I have a function that will create a new car struct; however, it is seg faulting when copying the char pointers. This is supposed to create a new node for a linked list.

Car *newCar(char *model, int year){
    Car *new = malloc(sizeof(Car));
    new->year = year;
    new->model = malloc(MAX_LENGTH*sizeof(char));
    strcpy(new->model, model);
    new->next = NULL;
    return new;
}
like image 691
kyle Avatar asked Mar 11 '13 06:03

kyle


Video Answer


2 Answers

For future reference this function fixed my issue...

Car *createCar(char *model, int year){
    Car *new = malloc(sizeof(Car));
    new->year = year;
    new->model = malloc(strlen(model)+1);
    strcpy(new->model, model);
    new->next = NULL;
    return new;
}
like image 166
kyle Avatar answered Sep 28 '22 05:09

kyle


Here your model is character pointer.

But strcpy requires two arguments - that should be array or character pointer to which memory allocated by malloc or calloc

But your strcpy(); takes one argument as character pointer which will not be accepted.

so make

new->model = malloc(strlen(model) + 1) and then write your strcpy () it will work.

like image 33
Hitesh Menghani Avatar answered Sep 28 '22 05:09

Hitesh Menghani