是否必须在C++中初始化指针?

Baa*_*ali 5 c c++ pointers dangling-pointer

t在为值赋值之前,是否必须在以下代码中进行初始化t?代码是否正确?

void swap(int *x, int *y)
{
    int *t;
    *t = *x;
    *x = *y;
    *y = *t;
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 9

你不需要指针开头:

void swap(int *x,int *y)
{
    int t; //not a pointer!
    t=*x;
    *x=*y;
    *y=t;
}
int a = 10, b = 20;
swap( &a, &b); //<-----------note : Needed &
Run Code Online (Sandbox Code Playgroud)

-

或者,您可能需要以下交换功能:

void swap(int & x,int & y) //parameters are references now!
{
    int t; //not a pointer!
    t=x;
    x=y;
    y=t;
}
int a = 10, b = 20;
swap(a,b); //<----------- Note: Not needed & anymore!
Run Code Online (Sandbox Code Playgroud)


Pra*_*rav 8

以下代码段是否正确?

Nopes!您的代码调用未定义的行为,因为您尝试取消引用野生指针.

 int *t;
 *t=*x; // bad
Run Code Online (Sandbox Code Playgroud)

试试这个

 int t; // a pointer is not needed here
 t=*x; 
Run Code Online (Sandbox Code Playgroud)

或这个

int *t = x; // initialize the pointer
Run Code Online (Sandbox Code Playgroud)


sha*_*oth 5

该代码包含未定义的行为:

int *t;
*t=*x; // where will the value be copied?
Run Code Online (Sandbox Code Playgroud)

除此之外没有意义 - 你需要一个临时变量来存储值,而不是指针.

int t; // not a pointer
t=*x;
*x=*y;
*y=t;
Run Code Online (Sandbox Code Playgroud)