我正在实现标准冒泡排序算法,并且我有一个关于指针的问题。
float *SortValues(float *p, size_t n)
{
float temp;
float didSwap;
float *current;
float *last = &p[n - 1];
float *start = p;
do
{
for (didSwap = 0, current = p; current < last; current++) {
if (current[0] > current[1]) {
temp = current[0];
current[0] = current[1];
current[1] = temp;
didSwap = 1;
}
}
--last;
}
while (didSwap);
return start;
}
使用其他指针来指向传入的指针的开始和/或结束时,我经常感到困惑。在上面的代码中,我将 current 设置为指向 p,并将 start 设置为指向 p。电流在整个循环中发生变化。既然 current 和 p 指向同一个东西,那么 p, and then start 如何最终变成指向与 current 相同的东西呢?
最佳答案
开始指向的位置不会改变。 start 所指向的是什么。
假设您有五个杯子,然后将一个球放入绿色杯子中。然后你告诉我把绿色杯子里的球换成一美元钞票。下次你查看绿色杯子时,它会包含一美元,而不是你放在那里的球。
最后一次经过while循环,当last == start
时,只执行for循环的初始化,以便在while循环时current == p
退出。
关于c - 跟踪指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2304967/