strcpy和数组的意外行为

strcpy和数组的意外行为,c,arrays,C,Arrays,我正在编写一个简单的字符串替换函数,我有一个非常有趣的错误。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 y

我正在编写一个简单的字符串替换函数,我有一个非常有趣的错误。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
这里

这里呢

streamBuf++;
您可以更改
streamBuf

因此,它将不再等于
main
中的
buf

因此,对
streamBuf
指向的数据的更改不再与对
buf
指向的数据的更改相同

如果要查看发生了什么,可以添加指针值的打印,如:

printf("buf is at %p\n", (void*)buf);
stripChars(buf, fromCh, toCh);

它是如何连接数组的

这是因为您正在更改函数中
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);
}
跟踪
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);
}

函数:
stripChars()
缺少所需的原型。原型应该插入文件顶部附近。谢谢!我真傻,没有注意到它。
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);
}