这个程序哪里有问题??
#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;}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'为标识判断一个字符串的结束,如果没有它库函数都没法正常使用了。