使用c+获取分段错误+;指针 >我试图通过运行下面的代码来熟悉C++指针。 #include <iostream> using namespace std; int main(void){ int* x; cout << &x << endl; return 0; } #包括 使用名称空间std; 内部主(空){ int*x; cout
您没有分配要分配的对象使用c+获取分段错误+;指针 >我试图通过运行下面的代码来熟悉C++指针。 #include <iostream> using namespace std; int main(void){ int* x; cout << &x << endl; return 0; } #包括 使用名称空间std; 内部主(空){ int*x; cout,c++,pointers,segmentation-fault,C++,Pointers,Segmentation Fault,您没有分配要分配的对象 int* x; x的值未指定,可以是任意值 *x = 100; 这是无效的 你必须写作 x = new int; *x = 100; 或 甚至 x = new int { 100 }; 提供编译器支持在C++ 2011中引入的运算符new的列表初始化。 您有未定义的行为。< /P> 第一个示例很好,因为&x(类型为int**)是堆栈分配指针的地址 并打印x的指针值,但 #include <iostream> using namespace std;
int* x;
x的值未指定,可以是任意值
*x = 100;
这是无效的
你必须写作
x = new int;
*x = 100;
或
甚至
x = new int { 100 };
提供编译器支持在C++ 2011中引入的运算符new的列表初始化。 您有未定义的行为。< /P>
第一个示例很好,因为&x
(类型为int**
)是堆栈分配指针的地址
并打印x的指针值,但
#include <iostream>
using namespace std;
int main(void){
int* x;
*x = 100;
cout << &x << endl;
return 0;
}
不完全是
std::cout当然有…
是一个未初始化的指针。因此,向其写入是未定义的行为。您必须首先初始化指针,方法是分配内存,如x
或将其指向现有变量,如x=new int;
。(请注意,当您x=&someExistingInt;
无法
时,因为您没有将指针初始化为指向可以存储值的有效内存位置。*x=100;
x = new int { 100 };
int y; int* x; x = &y; *x = 100; /*this means that y is now 100*/
int* x; *x = 100;
int* x = new int; *x = 100; std::cout << *x;
int* x = new int( 100 ); std::cout << *x;