简体   繁体   中英

what the difference between a function and *function?

I am confused in C as i am newbie. i know 1.1 is giving me maximum value and 1.2 is giving me maximum value variable address [ Picture ]. My question is how do i call *findmax function in main?

 int * findMax(int *a,int SIZE){

        int i,max=*a,address,add;

        for(i=0;i<SIZE;i++){

            if(max<*(a+i)){

                max=*(a+i);

                      }
            }
       //printf("maxium value is %d at index %x",max,&max);
       return &max;
        }

The * in the function definition is not a function pointer, it's the function's return type. The findMax function returns a pointer to integer. So you would call it just like any other functions in main:

int a[] = {1,2,3,4};
int *p = findMax(a, 4);

There is another problem, in your findMax function, you returned a pointer to a local variable, the storage of the variable will be no longer available when the function returns. Use it causes undefined behavior. So you can just return the max as an integer instead, if you really need to return a pointer, you should allocate it, or return a pointer that remains valid.

For example:

int* findMax(int *a,int SIZE){
    int i;
    int *max = a;
    for(i=0;i<SIZE;i++){
        if(*max<*(a+i)){
            max=a+i;
        }
    }
    return max;
}
#include<stdio.h>

int Max;
int* FindMax(int *a,int size)
{
    int i;
    Max=a[0];
    for(i=0;i<size;i++)
    {
        if(Max<=a[i])
            Max=a[i];
    }
    return &Max;
}

int main()
{
    int a[10]={10,19,9,127,45,189,47,222,90,158};
    printf("Address of Max Element:%p \n",FindMax(a,10));
    printf("Max of Elements:%d \n",Max);
    getchar();
    return 0;
}

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