j****k 发帖数: 91 | 1 二楼应该是这个题目的正解.
但是如果稍微改一下题目, 把pString1,2的定义改为:
char *pString1, *pString2;
pString1 = (char *)malloc(3*sizeof(char));
pString2 = (char *)malloc(21*sizeof(char));
strcpy(pString1,"AAA");
strcpy(pString2,"BBBBBBBBBBBBBBBBBBBB");
这样在for循环里走过第三步的时候pString1就已经到头了, 但为什么接下来的循环都
不会出错? 虽然说c++没有边界检测, 但程序在修改pString1越界指向的内容, 这难道
不该是Access violation吗? |
|
q*******i 发帖数: 353 | 2 int main()
{
char *pString1 = "AAA";
char *pString2 = "BBBBB";
int len = strlen(pString2);
char *NewpString1 = pString1 ;
for(int i=0;i
{
*pString1++ = *pString2++;
}
}
return 1;
}
运行之后是 Access violation 。 难道因为pString1 是 string literal,不能写?
要怎么改呢?谢谢 |
|
s***f 发帖数: 226 | 3 for(int i=0;i
{
pString1 = pString2;
}
} |
|
c***2 发帖数: 838 | 4 this loop won't do anything.
if you want p1 point to p2, one assignment is enough.
I guess you want to do:
pString1[i] = pString2[i];
in that case, you want to check whether p1 has enough memory to hold all of
p2.
otherwise, random memory overwrite may happen, will cause crash. |
|
s***f 发帖数: 226 | 5 careless mistake, yes you are right.
just pString1 = pString2; is enough
of |
|