1

I am trying to build a function that concatenate two strings and return the concatenated string

here is my current code

const char *myName();

int main(int argc, char *argv[]) {
    char *myname = myName();
    printf(myname);
    printf("\n");
}

const char *myName() {
    char *lastname = " lee";
    char *name = "adam";
    char fullname[sizeof(lastname) + sizeof(name)];
    char *test;
  
    strcpy(fullname, name);
    strcat(fullname, lastname);
    test = fullname;

    return test;
}

when I printf within the function

printf(test)

it prints out nicely. However, when I tried to print out the value after it has been returned

printf(myname)

nothing prints out.

Any idea how to fix this?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
A.Nassar
  • 27
  • 5
  • 1
    You are returning a pointer to a VLA stack array. The lifetime of that array does not extend past the function return. – Martin James Sep 05 '20 at 23:19
  • 1
    Actually, not a VLA, just a char array with automatic storage duration, so still it's gone after the return:( – Martin James Sep 05 '20 at 23:24

0 Answers0