I'm trying to concatenate multiple strings to create a longer phrase but I get weird, seemingly random, characters in front of the phrase when I try to print it. Here is the code:
char* str2 = argv[2];
int len2 = strlen(str2);
char* str3 = argv[3];
int len3 = strlen(str3);
printf("child PID(%d) receives Y = '%s' and Z= '%s' from the pipe\n",getpid(), str2, str3 );
//get the length of arguments 2 and 3 and create an array that is 1 larger than that (for the space between the two phrases)
//then concatenate them
int catLen = len2+len3;
char conc[catLen + 1];
strcat(conc, str2);
strcat(conc," ");
strcat(conc, str3);
printf("child PID(%d) concatenates Y and Z to generate Y' = '%s'\n",getpid(),conc);
int len1;
//get the length of the first command-line argument in the pipe
read(port[0],&len1,sizeof(len1));
//get the first command-line argument from the pipe
char str1[len1];
read(port[0], &str1,len1);
printf("child PID(%d) reads X from the pipe = '%s'\n",getpid(),str1);
//problems start when concatenating strings here
int totalLen = len1+catLen+1;
char phrase[totalLen];
strcat(phrase, str1);
printf("%s\n",phrase);
strcat(phrase," ");
printf("%s\n",phrase);
strcat(phrase,conc);
printf("child PID(%d) concatenates X and Y' to generate Z' = '%s'\n",getpid(),phrase);
I only encounter this issue when I try and concatenate the second set of strings, and I don't understand why. What is different between how I did it earlier and at the bottom the program?