请大家帮我看一下下面这两个简单的vc程序,有关字符串的

来源:百度知道 编辑:UC知道 时间:2024/06/06 09:15:20
#include <iostream>
using namespace std;

void main()
{
char str1[100]="This is just a test!";
char *str2=" My English name is .....!";

strcat(str1,str2);

cout<<str1;
}

//....................................................

#include <iostream>
using namespace std;

void main()
{
char *str1=This is just a test!";
char *str2=" My English name is .....!";

strcat(str1,str2);

cout<<str1;
}

为什么第一个程序正确,而第二个程序不正确?到底char *str1,char str[]有什么区别?

暂且假定 char *str1=This is just a test!"; 这句是对的。 因为事实上这句少了个引号。

char str1[100] 为str1 分配了100个字符的空间,存贮"This is just a test!"后还有足够的空间来存贮 str2,所在没有错。
而 char *str1="This is just a test!";中str1是指针,指向"This is just a test!";这个字符串,没有额外的空间来存贮 str2 ,所以会出错。