Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用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 - Fatal编程技术网

使用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;