gpt4 book ai didi

c - strcpy 和数组的意外行为

转载 作者:行者123 更新时间:2023-11-30 18:21:34 25 4
gpt4 key购买 nike

我正在编写一个简单的字符串替换函数,但有一个非常有趣的错误。 strcpy 不应该只覆盖 buf\streamBuf 值吗?它怎么连接数组呢?

int main()
{
char buf[512];
strcpy(buf, "Test\nInput\nHere\n");

char fromCh[2] = "\n";
char toCh[4] = "\\n ";
stripChars(buf, fromCh, toCh);
printf("Here's your buf: %s", buf);
return 0;
}

void stripChars(char *streamBuf, char* fromCh, char *toCh){
char strTemp[512];
int i=0;
int iLenFrom = strlen (fromCh);
int iLenTo = strlen (toCh);
while (*streamBuf)
{
if (strncmp (streamBuf, fromCh, iLenFrom) == 0)
{
strncpy (&(strTemp[i]), toCh, iLenTo);
i += iLenTo;
streamBuf += iLenFrom;
}
else
{
strTemp[i++] = *streamBuf;
streamBuf++;
}
}
strTemp[i] = '\0';
strcpy(streamBuf, strTemp);

printf("Here's your strTemp: %s \n", strTemp);
printf("Here's your streamBuf: %s \n", streamBuf);
}

这是我的输出

Here's your strTemp: Test\n Input\n Here\n  
Here's your streamBuf: Test\n Input\n Here\n
Here's your buf: Test
Input
Here
Test\n Input\n Here\n
Process finished with exit code 0

最佳答案

How come it concatenates arrays?

那是因为您正在更改函数中 streamBuf 指向的位置。

跟踪 streamBuf 指向的原始位置并在函数末尾使用它。

void stripChars(char *streamBuf, char* fromCh, char *toCh)
{
char* originalPointer = streamBuf;

...

streamBuf = originalPointer;
strcpy(streamBuf, strTemp);

printf("Here's your strTemp: %s \n", strTemp);
printf("Here's your streamBuf: %s \n", streamBuf);
}

关于c - strcpy 和数组的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40920664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com