Have a
typedef struct person {
char name[20]
char surname[20]
} person_t;
I need to create a string like XXXXXX:YYYYYY with the function like
char* personToString(person_t *p). I tried to make it:
char* personToString(person_t* p) {
int n1,n2;
n1=strlen(p->name);
n2=strlen(p->surname);
char *p = (char*) malloc((n1+n2+2)*sizeof(char));
strcat(p,puser->name);
strcat(p,":");
strcat(p,puser->surname);
return p;
}
This give me a reasonable output but I have some errors testing with valgrind! I also think that there is a way more classy to write the function!
sprintfinstead ofstrcat, likesprintf(p, "%s:%s", p->name, p->surname);, plus u overridep, u get it as parameter and then declare it aschar *and you dontfreeyourchar *sizeof(char)is not necessary since it's always1struct person *pinstead ofperson_t, sinceperson_tis an object and nottypedef?