Search code examples
cmallocduplicate-data

How to duplicate a structure into a pointer with malloc function [C-Programming]


I've tried to create a function that duplicate a structure into a pointer, but here is the issue, there is a char tab into the structure and I can't assign my original value to the new structure.

The function :

Planete *dupliquer(Planete *p){
  Planete *res;  
  res = (Planete*) malloc(sizeof(Planete));
  if(res == NULL){
    printf("Erreur d'allocation...\n");
    exit(1);
  }
  res->nomplanete = p->nomplanete;
  res->rayon = p->rayon;

  return res;
}

And here is the compilator error :

 error: incompatible types when assigning to type ‘char[20]’ from type ‘char *’
   res->nomplanete = p->nomplanete;
                   ^

Can you please help me, It will be very nice. Thanks for your support !


Solution

  • It looks like you do not need a separate malloc for nomplanete, because it is an array. In situations like that you should use strcpy, like this:

    strcpy(res->nomplanete, p->nomplanete);
    

    If all members of Planete are primitives or arrays, you could simply memcpy the entire thing, like this:

    res = malloc(sizeof(Planete)); // No need to cast
    if(res == NULL){
        printf("Erreur d'allocation...\n");
        exit(1);
    }
    memcpy(res, p, sizeof(Planete));
    

    If nomplanete were a pointer, you would have to do a separate malloc or use strdup:

    res->nomplanete = malloc(1+strlen(p->nomplanete));
    strcpy(res->nomplanete, p->nomplanete);