Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
strcat跳过字母或添加字母_C_String_Strcat - Fatal编程技术网

strcat跳过字母或添加字母

strcat跳过字母或添加字母,c,string,strcat,C,String,Strcat,我目前正在尝试创建一个应用程序来解析文件并更改一些字符串,但这并不重要 我目前正在尝试组合几个字符串,以产生一个统一的结果;然而,结果似乎与代码不一致。代码如下: /* Now let's recombine the strings */ strcat(slash+1, secondSlash+1); printf("\nFirst String: %s", toConvert); printf("\nSecond String: %s", slash+1); strcat(toConvert

我目前正在尝试创建一个应用程序来解析文件并更改一些字符串,但这并不重要

我目前正在尝试组合几个字符串,以产生一个统一的结果;然而,结果似乎与代码不一致。代码如下:

/* Now let's recombine the strings */
strcat(slash+1, secondSlash+1);
printf("\nFirst  String: %s", toConvert);
printf("\nSecond String: %s", slash+1);
strcat(toConvert, slash+1);
printf("\nFinal  String: %s", toConvert);
输出看起来有点像这样:

First  String: **1)** 
Second String: *rails new <websiteName> *
Final  String: **1)** *rails nw <webssiteName> *
第一个字符串:**1)**
第二个字符串:*rails new*
最终字符串:**1)****

为什么最终字符串不是两个原始字符串的精确连接?任何帮助都将不胜感激

正如@WhozCraig所说,这一问题违反了以下规定:

C99 7.23.3.1p2: "...If copying takes place between objects that overlap, the behavior is undefined."
因此,为了解决这个问题,我停止使用strcat函数,而是手动将字符串的所有元素向左移动。(以前我使用的策略是将连接点设置为
'\0'
strcat
将它们放在一起。这显然不是最优的

为了解决这个问题,我只需遍历整个char数组并将所有元素移到左边。以下是我的代码片段供参考:

/* Move all things to the left */
int index;
for (index = (slash+2-toConvert); index <= secondSlash-toConvert; index++)
    toConvert[index-1] = toConvert[index];

/* Now move all things after the secondSlash area left */
int secondIndex = secondSlash+2-toConvert;
while(toConvert[secondIndex] != '\0')
{
    toConvert[secondIndex-2] = toConvert[secondIndex];
    secondIndex++;
}
/* Add null char */
toConvert[secondIndex-2] = '\0';
/*向左移动所有对象*/
整数指数;

for(index=(slash+2-toConvert);index变量
slash
secondSlash
toConvert
是如何定义的?如何为它们分配内存?
char-toConvert[BUFSIZE];
char*slash=strchr(toConvert,“/”);
char*secondSlash=strchr(slash+2,“/”)
请记住,toConvert最终会被填充,斜杠和第二个斜杠都是以null结尾的。在本地计算机上工作得很好。顺便问一下,为什么斜杠+1?斜杠+1是因为我想在显示字符串时隐藏第一个字符。这很有趣,因为有时输出与预期相符,有时则不然。你不知道吗你认为这与BUFSIZ的限制有关吗?不过,我不认为这可以解释额外的字符。如果
斜杠
二次斜杠
指针在同一个缓冲区中,则可能与第一个
strcat
有重叠连接。C99 7.23.3.1p2:“…如果复制发生在重叠的对象之间,则行为是未定义的。”您可能需要对此进行研究。