C - create a string "from" struct parameter -


have

typedef struct person {     char name[20]     char surname[20] } person_t; 

i need create string xxxxxx:yyyyyy function char* persontostring(person_t *p). tried 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 reasonable output have errors testing valgrind! think there way more classy write function!

when malloc memory p memory hold garbage values. strcat append string after null character, in uninitialized string hold random values.

replace first strcat strcpy.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -