【发布时间】:2016-12-11 08:49:37
【问题描述】:
我需要澄清关于 C++ 中指针初始化基础知识的概念。根据我的理解,在使用指针放置一些值之前,必须为指针分配一个地址。
int *p;
*p=10; //inappropriate
cout << *p <<"\n";
这可能会显示正确的输出 (10),但这可能会在较大的程序中引起问题,因为 p 最初有垃圾地址,可以是任何东西,以后也可能在程序的其他地方使用。所以,我相信这是不正确,正确的做法是:
int *p;
int x=10;
p=&x; //appropriate
cout << *p <<"\n";
我的问题是,如果上面的理解是正确的,那么 char* 也一样吗?:
const char *str="hello"; // inappropriate
cout << str << "\n";
//OR
const string str1= "hello";
const char str2[6] ="world";
const char *str=str1; //appropriate
const char *st=str2; //appropriate
cout << str << st << "\n";
请指教
【问题讨论】:
-
int *p; *p = 10;的 char 等价物是char *s; *s = 'h';,而不是你写的