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)
你不需要指针开头:
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)
以下代码段是否正确?
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)
该代码包含未定义的行为:
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)
| 归档时间: |
|
| 查看次数: |
353 次 |
| 最近记录: |