简体   繁体   English

Function 在 C 中带有指针类型返回和指针参数

[英]Function with Pointer type return and pointer argument in C

I am trying to understand the passing pointer as an argument and pointer return type function.我试图将传递指针理解为参数和指针返回类型 function。 Similar concept works with string but not with integers.类似的概念适用于字符串,但不适用于整数。 Could someone please find issue in the below code and correct it.有人可以在下面的代码中找到问题并更正它。 The error message is错误信息是

cannot convert 'int**' to 'int*无法将“int**”转换为“int*”

' Many thanks in advance. ' 提前谢谢了。

#include <stdio.h>
int *findMax(int *num1, int *num2)
{
    if (*num1 > *num2)
    {
        return (num1);
    }
    else
    {
        return (num2);
    }
}

int main(void)
{
    int *_num1;
    *_num1 = 10;
    int *_num2;
    *_num2 = 12;
    int *bigger;
    bigger = findMax(&_num1, &_num2);
    return 0;
}

You create two int pointers - but they do not actually point at any int s so when you dereference them to assign values you get undefined behavior .您创建了两个int指针 - 但它们实际上并不指向任何int s,因此当您取消引用它们以分配值时,您会得到未定义的行为

int main(void)
{
    int _num1 = 10; // note: not a pointer
    int _num2 = 12; // note: not a pointer
    int *bigger;
    bigger = findMax(&_num1, &_num2); // here you take the addresses of the int:s
    printf("%d\n", *bigger);
}

cannot convert 'int**' to 'int*无法将“int**”转换为“int*”

That error saved you from a lot of pain.这个错误让你免于很多痛苦。 Since you declared the two variables as int* , taking the address of such a variable produces an int** which is not what your function accepts.由于您将这两个变量声明为int* ,因此获取此类变量的地址会产生一个int** ,这不是您的 function 接受的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM