简体   繁体   中英

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. 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*

' 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 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*

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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