【问题标题】:Weird characters when concatenating strings in c [duplicate]在c中连接字符串时出现奇怪的字符[重复]
【发布时间】: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 要求两个参数都是字符串。但是concphrase 都未初始化,因此不是有效的字符串。第一个只是偶然“起作用”,而不是因为它是正确的代码。添加conc[0] = 0;phrase[0] = 0;,然后将它们传递给各自的第一个strcat 调用。

标签: c string concatenation


【解决方案1】:

首先, 正如 Ptit Xav 指出的那样,conc 需要一个额外的空间字节。第一个字符串需要len1 字节,空格加上1,第二个字符串需要len2,然后是终止空字符。所以如果catLen = len1 + len2,那么你应该声明char cond[catLen + 2];(或者以某种等效的方式改变catLen的计算)。


接下来,当你声明一个像char conc[catLen + 2]; 这样的本地数组而不初始化它时,它包含垃圾。如果您随后尝试将strcat 连接到它,您将连接到垃圾上。如果垃圾恰好不包含任何空字节,那么strcat 将溢出数组搜索空字节,导致未定义的行为(这是非常糟糕的)。

所以要么首先使用strcpy 而不是strcat

char conc[catLen + 2];
strcpy(conc, str2);  // note strcpy here
strcat(conc," ");
strcat(conc, str3);

或者在开始之前将数组的第一个字符设置为空字符,使其变为空字符串:

char conc[catLen + 2];
conc[0] = '\0';     // conc now contains an empty string
strcat(conc, str2);
strcat(conc," ");
strcat(conc, str3);

也可以初始化数组:

char conc[catLen + 2] = "";
strcat(conc, str2);
strcat(conc," ");
strcat(conc, str3);

但是这会导致程序用空字节填充整个数组conc,而你实际上只需要一个,所以效率很低。

【讨论】:

  • 这解决了问题。感谢您的帮助!
  • 我认为你必须给 catlen 加 1,因为你在 str2 和 str3 之间加了一个空格。所以 conc 数组的大小应该是:len2(str2) + 1(space)+len3(str3)+1(\0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-20
  • 1970-01-01
  • 2017-02-18
  • 2021-01-20
  • 1970-01-01
  • 2021-12-13
相关资源
最近更新 更多