c++ - 将指针作为参数传递给函数

标签 c++

我需要帮助来理解指针在下面的代码中是如何工作的,因为我真的很困惑。代码是关于从给定数组中找到最大值和最小值。我知道这个问题也可以通过使用结构来解决但我想了解指针的使用

#include<stdio.h>
int max2,min2,max,min,maximum,minimum;
int Maxmin(int a[],int *max,int *min,int i,int j)
{
    if(i==j)
    {
        return *max=*min=a[i];
    }
    else if(i==j-1)
    {
        if(a[i]<a[j])
        {
            *max=a[j];
            *min=a[i];
        }
        else
        {
            *max=a[i];
            *min=a[j];
        }
    }
    else
    {
        int mid=(i+j)/2;
        Maxmin(a,max,min,i,mid);
        Maxmin(a,&max2,&min2,mid+1,j);

    }
    if(*max<max2)
    {
        *max=max2;
    }

    if(*min>min2)
    {
        *min=min2;
    }

}

int main()
{
    int a[]={4,30,2,100,230};
    Maxmin(a,&max,&min,0,4);
    printf("%d %d",max,min);
}

最佳答案

调用方:

maxmin 是整型变量。 &max&min 是这些int变量的内存地址。

从被调用方:

int *maxint *minMaxmin 中声明为指向 int 的指针。让我们把它看成指针包含一个内存地址。指向 int 的指针包含 int 变量的内存地址。

*max*min 是访问内存地址内容(解引用指针)的方式。由于您有一个指向 int 的指针,因此您将从该操作中读取一个 int。

此代码的关键是要知道,如果您在 Maxmin 中修改 *max*min,您将更改maxmin 的值在函数外部,因为您直接使用这些全局变量的内存内容。

关于c++ - 将指针作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54307560/

相关文章:

c++ - 如何访问 friend 类方法?

c++ - 多重定义和命名空间

C++ Boost线程库拉入整个开发环境

c++ - 宏使用建议

c++ - 具有奇怪的重复模板模式的数组?

c++ - 在 C++ 函数中使用数组作为参数

c++ - 为什么模板函数中的 std::is_array 不区分 int 和 array 类型?

c++ - SSL_shutdown() 返回 -1 且 errno 为 0

c++ - 从后面访问 vector

c++ - QLabel在调整大小时切断文本