首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

这个程序哪里有有关问题?

2012-05-14 
这个程序哪里有问题??C/C++ code#include iostreamusing namespace stdvoid test1(){char str[10]char

这个程序哪里有问题??

C/C++ code
#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;}


运行结果是对的,但是有问题的。

[解决办法]
char str[10];
char *str1 = "0123456789";
strcpy(str, str1);
str 空间不足

test3函数也有类似问题
[解决办法]
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];

[解决办法]
strcpy(str, str1);这个都可以是常错集了。。
[解决办法]
字符串一般系统要求以'\0'作为结束符。所以你的test1里面的那个数组荣不下0123456789这个字符串的。所以会出问题。
C/C++ code
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;}
[解决办法]
字符串需要一个终止符'\0',所以需要额外的一个位置来放这个符号。
否则有可以造成打印出乱码,而且strcpy等库函数都是以'\0'为标识判断一个字符串的结束,如果没有它库函数都没法正常使用了。

热点排行