[英]Unexpected behaviour with strcpy and arrays
I am writing a simple string substitution function and I have a quite interesting error. 我正在编写一个简单的字符串替换函数,但有一个非常有趣的错误。 Shouldn't strcpy just overwrite the buf\\streamBuf value?
strcpy不应该只覆盖buf \\ streamBuf值吗? How come it concatenates arrays?
它如何连接数组?
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);
}
and here's my output 这是我的输出
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
Here 这里
streamBuf += iLenFrom;
and here 和这里
streamBuf++;
you change streamBuf
您更改
streamBuf
Consequently it will no longer be equal to buf
in main
. 因此,它将不再等于
main
buf
。
So changes to data pointed to by streamBuf
is no longer the same as changing data pointed to by buf
因此,对
streamBuf
指向的数据的更改不再与更改buf
数据的更改相同
If you want to see what happens, you can add prints of the pointer values, like: 如果要查看会发生什么,可以添加指针值的输出,例如:
printf("buf is at %p\n", (void*)buf);
stripChars(buf, fromCh, toCh);
and 和
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);
}
How come it concatenates arrays?
它如何连接数组?
That's because you are changing where streamBuf
points to in the function. 那是因为您正在更改
streamBuf
指向函数中的位置。
Keep track of the original location of where streamBuf
points to and use it at the end of the function. 跟踪
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.