字符串如此连接为何不可?

wyylbl 2002-05-09 03:17:05
#include <iostream.h>
#include <string.h>
void main()
{ char *s1="first";
char s2[20]="second";
char s3[10]="third";
char s4[30];
strcpy(s4,s1);
strcat(s4,s2);
strcat(s4,s3);
cout<<"s4:"<<s4<<endl;
cout<<strcat(s1,strncat(s2,s3,3))<<endl;//运行到该语句时出现错误,错在哪里?

}
...全文
20 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
shuimushao 2002-05-09
  • 打赏
  • 举报
回复
呵呵,不好意思,刚才贴错了
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
void main()
{char* s="first" ;
char* s1=(char*)malloc(sizeof(char)*30);
strcpy(s1,s);
char s2[20]="second";
char s3[10]="third";
char s4[30];
strcpy(s4,s1);
strcpy(s4,s2);
strcat(s4,s3);
cout<<"s4:"<<s4<<endl;
cout<<strcat(s1,strncat(s2,s3,3))<<endl;//运行到该语句时出现错误,错在哪里?

}
shuimushao 2002-05-09
  • 打赏
  • 举报
回复
这样就行
#include <string.h>
#include <stdlib.h>
void main()
{char* s="first" ;
char* s1=(char*)malloc(sizeof(char)*30);

char s2[20]="second";
char s3[10]="third";
char s4[30];
strcpy(s4,s1);
strcpy(s4,s2);
strcat(s4,s3);
cout<<"s4:"<<s4<<endl;
cout<<strcat(s1,s2)<<endl;
cout<<strcat(s1,strncat(s2,s3,3))<<endl;//运行到该语句时出现错误,错在哪里?

}
shuimushao 2002-05-09
  • 打赏
  • 举报
回复
其实就是没有分配足够的空间而已。
char s5[30]="first";
char* s1=s5;
这样就可以,当然也可以用malloc,和relloc来进行分配
operaphantom 2002-05-09
  • 打赏
  • 举报
回复
s1空间只读,需自己分配内存,用数组或malloc()
我正在讨论这个问题,你到我的问题上看看吧
http://www.csdn.net/Expert/TopicView1.asp?id=702364
frog_huang 2002-05-09
  • 打赏
  • 举报
回复
s1是指针变量,它根本没有空间足够的空间来容纳,先malloc一段空间,并让s1指向它,然后才用 能strcpy(s1,...)或strcat(s1,...),否则出错
tinymole 2002-05-09
  • 打赏
  • 举报
回复
改成

...
char a[50]="first";
char *s1=a;
...

可以了吧?
kof99th 2002-05-09
  • 打赏
  • 举报
回复
s1不可写,改为数组方式
Francky 2002-05-09
  • 打赏
  • 举报
回复
char *s1 = "first";

是放在const 数据段中是只读的,不能改.
neccui 2002-05-09
  • 打赏
  • 举报
回复
s1没有足够的空间,会溢出,而且"first"很有可能放在只读数据段。

所以应该分配肯定可写和足够的空间。

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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