在给t
赋值之前,是否必须初始化以下代码中的t
?这段代码正确吗?
void swap(int *x, int *y)
{
int *t;
*t = *x;
*x = *y;
*y = *t;
}
在给t
赋值之前,是否必须初始化以下代码中的t
?这段代码正确吗?
void swap(int *x, int *y)
{
int *t;
*t = *x;
*x = *y;
*y = *t;
}
您一开始不需要指针:
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 &
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!
int *t;
*t=*x; // bad
int t; // a pointer is not needed here
t=*x;
或者是这个
int *t = x; // initialize the pointer
这段代码存在未定义的行为:
int *t;
*t=*x; // where will the value be copied?
int t; // not a pointer
t=*x;
*x=*y;
*y=t;
如果你只想让指针指向已经初始化的数据,那么就不需要初始化它。但是你需要使用malloc函数之一来分配足够的堆空间以存放一个整数。
C/C++中适当且高效的交换方式是
void swap(int *x, int *y) {
int *t = x;
x = y;
y = t;
}
你可以在这里找到正确的做法。
#include <stdio.h>
void swap(int *i, int *j)
{
int t;
t = *i;
*i = *j;
*j = t;
}
基本上,sharptooth已经向您解释了原因,但在那里您会找到更多有关进行此类交换时背景中发生的情况的细节和解释。希望这有助于澄清您的想法。
指针的使用是正确的。
只有引用需要在声明时进行初始化(或在实例成员的构造函数中进行初始化)。
编辑:但是你的代码存在错误,你不应该对参数进行解引用操作(例如,int *ptr = otherPtr;
是可以的,而不是 int *ptr = *otherPtr;
)
int *t;
*t=*x;
t
没有指向任何有效的位置,因此无法进行解引用。
在给指针
t
赋值之前,是否必须进行初始化?
是的,需要将其初始化/赋值为指向有效内存位置的指针。否则它可能会指向垃圾并导致未定义行为在解引用时发生。
swap(p,q)
等同于std::swap(*p,*q)
,但不是std::swap(p,q)
,后者将交换指针而不是内容) - David Rodríguez - dribeas