在声明时可以将指针赋值给一个变量吗?像这样:
int * p = &(1000)
在声明时可以将指针赋值给一个变量吗?像这样:
int * p = &(1000)
是的,你可以在声明时将指针初始化为一个值,但你不能这样做:
int *p = &(1000);
&是地址运算符,你不能将其应用于常量(尽管如果可以的话,那将会很有趣)。请尝试使用另一个变量:
int foo = 1000;
int *p = &foo;
或类型转换:
int *p = (int *)(1000); // or reinterpret_cast<>/static_cast<>/etc
int *p=(int *)100;
。然后输出结果是类似于000003E8
**的东西。 - Ravistatic_cast
、dynamic_cast
、const_cast
和reinterpret_cast
,对于单行初始化示例int *p = X_cast<int*>(1000);
,只有C风格强制转换和函数风格强制转换(使用(type)object
或type(object)
,可以替换其他类型的强制转换)和reinterpret_cast
有效。有任何想法可能是什么原因吗?为什么我们不能在这里执行static_cast
? - CreativiTimothy这怎么样:
// Creates a pointer p to an integer initialized with value 1000.
int * p = new int(1000);
已测试并且可行。;-)
new
)与上述方法有什么不同之处? - AjB对我来说,问题中有两件事不清楚。你想将指针设置为特定值(即地址),还是想让指针指向某个特定变量?
在后一种情况下,您可以使用取地址运算符。然后指针的值将被设置为some_int_variable
的地址。
int *p = &some_int_variable;
*p = 10; // same as some_int_variable = 10;
int *p = 1000;
由于编译器不会将int解释为地址,因此您必须明确告诉编译器它应该这样做:
int *p = reinterpret_cast<int*>(1000);
嗯,我认为你不能像那样对一个常量取非const地址。
但这样可以:
int x = 3;
int *px = &x;
cout << *px; // prints 3
const int x = 3;
const int *px = &x;
const int *pfoo = reinterpret_cast<const int*>(47);