Filling a char pointer in a structure

I defined the "car" structure with the model (char * model) and the model year (int year). I have a function that will create a new car structure; however, when copying char pointers, it is disabled. It is supposed to create a new node for the 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; } 
+6
source share
4 answers

For future reference, this feature fixed my problem ...

 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; } 
+2
source

You can try the following:

 new->model = model == NULL ? NULL : strdup(model); 

this will prevent you from error if the model is NULL, otherwise malloc you must specify the exact amount of space and strcopy it; plus, it allows you free(new->model) at the end in all cases.

+4
source

Here your model is a symbol pointer.

But strcpy requires two arguments - it must be an array or character pointer to which memory allocated by malloc or calloc

But your strcpy(); accepts one argument as a character pointer that will not be accepted.

so do

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

+3
source

Look at the code below and compare it with your program, make sure that you find out what is wrong with your program.

 #include <stdio.h> #include <string.h> typedef struct car{ char *model; int year; }Car; Car * newCar(char *, int ); int main() { Car *benz = newCar("S-class",1990); printf("\nModel = %s\n",benz->model); printf("\nYear = %d\n",benz->year); } Car * newCar(char *model, int year) { Car *new = malloc(sizeof(Car)); new->year = year; new->model = malloc(strlen(model)); strcpy(new->model, model); return new; } 
+1
source

All Articles