C++ 中是否必须初始化指针?
在给t
赋值之前,是否必须在下面的代码中初始化t
?代码正确吗?
void swap(int *x, int *y)
{
int *t;
*t = *x;
*x = *y;
*y = *t;
}
Is it compulsory to initialize t
in the following code, before assigning value to t
? Is the code correct?
void swap(int *x, int *y)
{
int *t;
*t = *x;
*x = *y;
*y = *t;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您不需要以指针开头:
--
或者,您可能需要以下交换函数:
You don't need pointer to begin with:
--
Or maybe, you want the following swap function:
不!您的代码调用未定义的行为,因为您试图取消引用野指针。
试试这个
或者这个
Nopes! Your code invokes Undefined behaviour because you are trying to dereference a wild pointer.
Try this rather
or this
该代码包含未定义的行为:
除此之外它没有任何意义 - 您需要一个临时变量来存储值,而不是指针。
That code contains undefined behavior:
Besides that it makes no sense - you need a temporary variable to store the value, not the pointer.
对于指针来说这是正确的。
只有引用需要在声明时初始化(或在实例成员的构造函数中)。
编辑:但是您的代码中有错误,您不应该取消引用您的参数(即
int *ptr = otherPtr;
很好,而不是int *ptr = *otherPtr;
)It's correct for a pointer.
Only references need to be initialized upon declaration (or in a constructor for instance members).
EDIT: but you got errors in your code, you shouldn't be dereferencing your parameters (ie
int *ptr = otherPtr;
is fine, notint *ptr = *otherPtr;
)如果您只是想让指针指向已经初始化的数据,那么您不需要初始化它。不过,您的做法是,您想要使用 malloc 函数之一为整数分配足够的堆空间。
在 C/C++ 中进行交换的正确、有效的方法是
If you just want to make your pointer point to already-initialized data, then you don't need to initialize it. The way you do it, though, yes, you want to use one of the malloc functions to allocate enough heap space for an integer.
The proper, efficient way, to do swapping in C/C++ is
您可以在此处找到执行此操作的正确方法
基本上,sharptooth已向您解释了原因,但是在那里,您将找到一些有关进行此类交换时后台发生的情况的更多详细信息和解释。希望它有助于理清您的想法。
You can find the right way of doing this here
Basically the reason has been explained to you by sharptooth but there you will find some more details and explanations about what happens in background when you do such a swap. Hope it helps to clear your ideas.
t
未指向任何能够取消引用的有效位置。是的,初始化/分配以指向有效的内存位置。否则它会指向哪里。它可能会指向垃圾并导致取消引用上的未定义行为。
t
is not pointing to any valid location to be able to dereference.Yes, initializing / assigning to point to a valid memory location. Else where would it point to. It might some point to garbage and lead to undefined behavior on dereferencing.