-1

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;
        }
Jordan
  • 505
  • 5
  • 13

2 Answers2

5

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;
}
fluter
  • 13,238
  • 8
  • 62
  • 100
1
#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;
}
Yugesh
  • 59
  • 1
  • 8
  • It's better to declare function at file scope, not inside main – M.M Apr 25 '16 at 05:34
  • Is this a better on?? @M.M – Yugesh Apr 25 '16 at 05:39
  • Better, but it isn't necessary that `Max` be global. Just declare it in `main` and pass it as a parameter to `FindMax` (e.g. `FindMax (int *a, int size, int max)` (change the name as needed within the function) Also note, the standard coding style for C avoids `caMelCase` variables in favor of all *lower-case*. See e.g. [**NASA - C Style Guide, 1994**](http://homepages.inf.ed.ac.uk/dts/pm/Papers/nasa-c-style.pdf) – David C. Rankin Apr 25 '16 at 05:52