【发布时间】:2021-11-19 03:28:27
【问题描述】:
我正在尝试连接多个字符串以创建更长的短语,但是当我尝试打印时,短语前面出现了奇怪的、看似随机的字符。代码如下:
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);
我只在尝试连接第二组字符串时遇到这个问题,我不明白为什么。我之前的做法和程序底部的做法有什么不同?
【问题讨论】:
-
他们都有同样的问题。
strcat要求两个参数都是字符串。但是conc和phrase都未初始化,因此不是有效的字符串。第一个只是偶然“起作用”,而不是因为它是正确的代码。添加conc[0] = 0;和phrase[0] = 0;,然后将它们传递给各自的第一个strcat调用。
标签: c string concatenation