gpt4 book ai didi

c - 为什么变量在递归调用中获得相同的地址?

转载 作者:太空宇宙 更新时间:2023-11-04 08:27:00 25 4
gpt4 key购买 nike

/* Calculating minimum and maximum element out of a list of elements using Recursion
Input: A list of numbers
Output: Minimum and Maximum number
*/

#include<stdio.h>

int a[8]={6,2,3,9,1,0,11,8},size=8;

int * minmax(int beg,int end)
{
int res[2],*x,*y,mid;
printf("%d %d %p:",beg,end,res);
if(beg==end)
{
res[0]=a[beg];
res[1]=a[beg];
return res;
}
if(end-beg==1)
{
if(a[beg]<=a[end])
{
res[0]=a[beg];
res[1]=a[end];
}
else
{
res[0]=a[end];
res[1]=a[beg];
}
printf("%d %d",res[0],res[1]);
printf("\n");
return res;
}
printf("\n");
mid=(beg+end)/2;
x=minmax(beg,mid);
y=minmax(mid+1,end);
if(x[0]<=y[0])
res[0]=x[0];
else if(x[0]>y[0])
res[0]=y[0];
if(x[1]<=y[1])
res[1]=y[1];
else if(x[1]>y[1])
res[1]=x[1];
printf("OUT: %d %d %d %d WIN: %d %d\n",x[0],y[0],x[1],y[1],res[0],res[1]);
return res;
}

int main()
{
int i,j,min,max,*ans;
ans=minmax(0,size-1);
printf("Ans=%d %d",ans[0],ans[1]);
return 0;
}

在上面使用递归获取最小和最大元素的代码中,数组 res 在连续的递归调用中获取相同的地址,如下所示:

    0 7 0xbfa9cb08:
0 3 0xbfa9cac8:
0 1 0xbfa9ca88:2 6
2 3 0xbfa9ca88:3 9
OUT: 3 3 9 9 WIN: 3 9
4 7 0xbfa9cac8:
4 5 0xbfa9ca88:0 1
6 7 0xbfa9ca88:8 11
OUT: 8 8 11 11 WIN: 8 11
OUT: 8 8 11 11 WIN: 8 11
Ans=8 11

在函数调用 minmax(0,1)minmax(2,3) res 得到相同的地址,这就是它创建的原因问题。在 minmax(4,5)minmax(6,7)

可以观察到类似的事情

为什么会这样,我该如何修改程序以获得最小值和最大值

最佳答案

您不能返回自动变量的地址。作为WhozCraig评论,是undefined behavior .顺便说一句,如果您启用所有警告和调试信息(例如,如果使用 GCC,则使用 gcc -Wall -Wextra -g 进行编译)您会收到警告。

你应该返回一个 struct两个数字,例如声明为

struct myminmax_st {
int mymin;
int mymax;
};
struct myminmax_st minmax(int *arr, int beg, int end);

struct myminmax_st
minmax(int *arr, int beg, int end)
{
struct myminmax_st res = { INT_MIN, INT_MAX };
if(beg==end) {
res.mymin = arr[beg];
res.mymax = arr[end];
return res;
}

我留给你来完成这个例程。你需要#include <limits.h>得到INT_MIN & INT_MAX

注意在 Linux/x86-64 上 ABI指定返回 struct使用两个整数真的很快:它们在两个寄存器中返回。 (这特定于具有两个标量场的 struct)。

您可以改为将生成的最小值和最大值的地址作为正式参数传递,如 MiteshMS answer 中所述。 (但在 Linux/x86-64 上这可能会更慢,因为那样你会遍历内存)。

同样在 C 中,数组会退化为指针,因此您不能返回数组(除非您将其打包在一些 struct 中);您可以返回指向某个数组的指针(通常是 heap-allocatedmalloc )。在那种情况下 - 一个堆分配的数组,作为指针返回 - 你需要一些关于谁负责 free记录约定 -正在处理它。

关于c - 为什么变量在递归调用中获得相同的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30025171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com