繁体   English   中英

strcpy和数组的异常行为

[英]Unexpected behaviour with strcpy and 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

这里

streamBuf += iLenFrom;

和这里

streamBuf++;

您更改streamBuf

因此,它将不再等于main buf

因此,对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);
}

它如何连接数组?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM