我在处理 char 指针时感到困惑。请看下面的代码:
class Person
{
char* pname;
public:
Person(char* name)
{
//I want to initialize 'pname' with the person's name. So, I am trying to
//achieve the same with different scenario's
//Case I:
strcpy(pname, name); // As expected, system crash.
//Case II:
// suppose the input is "ABCD", so trying to create 4+1 char space
// 1st 4 for holding ABCD and 1 for '\0'.
pname = (char*) malloc(sizeof(char) * (strlen(name)+1) );
strcpy(pname, name);
// Case III:
pname = (char*) malloc(sizeof(char));
strcpy(pname, name);
}
void display()
{
cout<<pname<<endl;
}
};
void main()
{
Person obj("ABCD");
obj.display();
}
对于案例 I:正如预期的那样,系统崩溃。
案例二的输出:
A B C D
案例 III 的输出:
A B C D
所以,我不确定为什么案例 II 和 III 会产生相同的输出!!!!..... 我应该如何在一个类中初始化一个 char 指针?