strcpy和数组的意外行为

时间:2016-12-01 21:25:09

标签: 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 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

2 个答案:

答案 0 :(得分:3)

下面

streamBuf += iLenFrom;

在这里

streamBuf++;

您更改了streamBuf

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

因此streamBuf指向的数据更改不再与更改buf

指向的数据相同

如果你想看看会发生什么,你可以添加指针值的打印,如:

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

void stripChars(char *streamBuf, char* fromCh, char *toCh){
    printf("streamBuf is at %p\n", (void*)streamBuf);
    ....
    ....
    printf("streamBuf is at %p\n", (void*)streamBuf);
    printf("Here's your streamBuf: %s \n", streamBuf);
}

答案 1 :(得分:3)

  

为什么它会连接数组?

那是因为你正在改变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);
}