字符串用指针复制的一个小问题

xfate 2009-10-30 05:38:29
#include<iostream>
using namespace std;
int main(void)
{
char *p="qqweqweq";
char *q="asd";
while(*q)
{
*p++=*q++;
}
*p='\0';
cout<<q<<endl;
}

为什么会访问冲突,把*q复制给*p,而且两个指针都初始化了?
...全文
116 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhaocong981107 2011-10-10
  • 打赏
  • 举报
回复
都不错哎
yinfuyong 2009-10-30
  • 打赏
  • 举报
回复
#include<iostream>
using namespace std;
int main(void)
{
char a[]="qqweqweq";
char b[]="asd";
char *q=b;
char *p=a;
while(*q)
{
*p++=*q++;
}
*p='\0';
cout<<a<<endl;
}
yinfuyong 2009-10-30
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 huangyong19870618 的回复:]
引用 4 楼 huangyong19870618 的回复:
引用 1 楼 xingzhe2001 的回复:
两个指针指向的都是常量字符串,是只读的内存区,所以会出错,你要这么改,那么字符串都在栈上,就可以随便改了。

C/C++ code#include <iostream>usingnamespace std;int main(void)
{char p[]="qqweqweq";char q[]="asd";while(*q)
    {*p++=*q++;
    }*p='\0';
    cout < <q < <endl;
}


我在VS2005上编译你这个怎么说++需要左值  怎么回事??


啊  查到了 数组指针不能被++!!
[/Quote]
===================================================================
也就是说不能这么写了吗?
bean11222 2009-10-30
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 huangyong19870618 的回复:]
引用 1 楼 xingzhe2001 的回复:
两个指针指向的都是常量字符串,是只读的内存区,所以会出错,你要这么改,那么字符串都在栈上,就可以随便改了。

C/C++ code#include <iostream>usingnamespace std;int main(void)
{char p[]="qqweqweq";char q[]="asd";while(*q)
    {*p++=*q++;
    }*p='\0';
    cout < <q < <endl;
}

我在VS2005上编译你这个怎么说++需要左值  怎么回事??
[/Quote]

啊 查到了 数组指针不能被++!!
kernelshell 2009-10-30
  • 打赏
  • 举报
回复
#include<iostream>
using namespace std;
int main(void)
{
char p[]="qqweqweq";
char q[]="asd";
char *m,*n;
m = p;
n = q;
while(*m)
{
*(m++) = *(n++);
}
*m='\0';
for (int i = 0; i < 3;i++)
cout<<*(n+i)<<endl;
return 0;
}
xfate 2009-10-30
  • 打赏
  • 举报
回复
哦,明白,唉,前一周时也只知道指针定义字符串常量时,是只读的,现在怎么就忘了。以后用const char *p来定义了。。。。
改了一下
#include<iostream>
using namespace std;
int main(void)
{
char a[]="qqweqweq";
char b[]="asd";
char *q=b;
char *p=a;
while(*q)
{
*p++=*q++;
}
*p='\0';
p=p-strlen(b);
cout<<p<<endl;
}
bean11222 2009-10-30
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 xingzhe2001 的回复:]
两个指针指向的都是常量字符串,是只读的内存区,所以会出错,你要这么改,那么字符串都在栈上,就可以随便改了。

C/C++ code#include<iostream>usingnamespace std;int main(void)
{char p[]="qqweqweq";char q[]="asd";while(*q)
{*p++=*q++;
}*p='\0';
cout<<q<<endl;
}
[/Quote]
我在VS2005上编译你这个怎么说++需要左值 怎么回事??
li32768 2009-10-30
  • 打赏
  • 举报
回复
你的指针最后已经移到最后一个字符了,你输出不崩溃就不错了
x396448534 2009-10-30
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 xingzhe2001 的回复:]
两个指针指向的都是常量字符串,是只读的内存区,所以会出错,你要这么改,那么字符串都在栈上,就可以随便改了。
C/C++ code#include<iostream>usingnamespace std;int main(void)
{char p[]="qqweqweq";char q[]="asd";while(*q)
{*p++=*q++;
}*p='\0';
cout<<q<<endl;
}
[/Quote]真是高手…
xingzhe2001 2009-10-30
  • 打赏
  • 举报
回复
两个指针指向的都是常量字符串,是只读的内存区,所以会出错,你要这么改,那么字符串都在栈上,就可以随便改了。

#include<iostream>
using namespace std;
int main(void)
{
char p[]="qqweqweq";
char q[]="asd";
while(*q)
{
*p++=*q++;
}
*p='\0';
cout<<q<<endl;
}

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧