这个程序哪里有问题??

过往记忆
博客专家认证
2012-05-12 02:18:27
#include <iostream>

using namespace std;

void test1(){
char str[10];
char *str1 = "0123456789";
strcpy(str, str1);
cout << str << "\t" << str1 << endl;
}

void test2(){
char str[10], str1[10];
for(int i = 0; i < 9; i++){
str1[i] = 'a' + i;
}
str1[9] = '\0';
strcpy(str, str1);
cout << str << "\t" << str1 << endl;
}

void test3(char *str1){
char str[10];
if(strlen(str1) <= 10){
strcpy(str, str1);
}
cout << str << "\t" << str1 << endl;
}

int main(){

test1();
test2();
char *str = "0123456789";
test3(str);
return 0;
}


运行结果是对的,但是有问题的。
...全文
119 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
tongzhipeng5699 2012-05-12
  • 打赏
  • 举报
回复
字符串需要一个终止符'\0',所以需要额外的一个位置来放这个符号。
否则有可以造成打印出乱码,而且strcpy等库函数都是以'\0'为标识判断一个字符串的结束,如果没有它库函数都没法正常使用了。
W170532934 2012-05-12
  • 打赏
  • 举报
回复
字符串一般系统要求以'\0'作为结束符。所以你的test1里面的那个数组荣不下0123456789这个字符串的。所以会出问题。


void test1(){
char str[12];
char *str1 = "0123456789";
strcpy(str, str1);
cout << str << "\t" << str1 << endl;
}

void test2(){
char str[10], str1[10];
for(int i = 0; i < 9; i++){
str1[i] = 'a' + i;
}
str1[9] = '\0';
strcpy(str, str1);
cout << str << "\t" << str1 << endl;
}

void test3(char *str1){
char str[11];
if(strlen(str1) <= 10){
strcpy(str, str1);
}
cout << str << "\t" << str1 << endl;
}

int main(){

test1();
test2();
char *str = "0123456789";
test3(str);
return 0;
}
xiao0915 2012-05-12
  • 打赏
  • 举报
回复
strcpy(str, str1);这个都可以是常错集了。。
诶呦 2012-05-12
  • 打赏
  • 举报
回复
void test1(){
char str[10];
char *str1 = "0123456789";
strcpy(str, str1);
cout << str << "\t" << str1 << endl;
}
Remarks
The strcpy function copies strSource, including the terminating null character, to the location specified by strDestination.
str[]没有结束符,char str[11];
justkk 2012-05-12
  • 打赏
  • 举报
回复
char str[10];
char *str1 = "0123456789";
strcpy(str, str1);
str 空间不足

test3函数也有类似问题

64,649

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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