0
void swap (int *px, int *py) {
int temp;
temp = *px;
*px = *py;
*py = temp;
}

这将交换两个变量,这对我来说看起来不错。

现在如果我把它改成

void swap (int *px, int *py) {
int *temp;
*temp = *px;
*px = *py;
*py = *temp;
}

注意 int *temp

无论如何,这仍然有效,但是 temp 在没有初始化的情况下被取消引用。

这不适合什么价值?

就像如果我想创建一个名为 proc 的方法,我怎么能保证程序会崩溃?我想我应该在堆栈上留下一些东西。

int main () {
int a = 1, b = 2;
proc(/* Some args might go here */);
swap(&a, &b);
}
4

2 回答 2

1

既然int是基本类型,为什么不...

void swap (int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; }

于 2013-03-19T11:07:06.393 回答
0

您所做的是依靠好运气:未初始化的会int *temp;使用堆栈中的一些垃圾,如果您足够幸运,它的取消引用将使用 SIGSEGV(Windows 上的 AccessViolation)使程序崩溃,否则(而且更糟!)它会破坏一些现有内存位置的数据可能对程序至关重要,但它会在很久以后作为一个神秘的 geizenbug 出现。

因此,未初始化指针的行为完全取决于堆栈的状态,这实际上是随机的:取决于之前调用过的函数以及它们使用的数据量以及它们的局部变量。

于 2013-03-19T11:11:25.273 回答