简体   繁体   English

函数和* function有什么区别?

[英]what the difference between a function and *function?

I am confused in C as i am newbie. 我对C感到困惑,因为我是新手。 i know 1.1 is giving me maximum value and 1.2 is giving me maximum value variable address [ Picture ]. 我知道1.1给我最大值,而1.2给我最大值变量地址[ 图片 ]。 My question is how do i call *findmax function in main? 我的问题是如何在main中调用* findmax函数?

 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. findMax函数返回一个指向整数的指针。 So you would call it just like any other functions in main: 因此,您可以像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. 还有一个问题,在findMax函数中,您返回了一个指向局部变量的指针,该函数返回时该变量的存储将不再可用。 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. 因此,您可以只将max作为整数返回,如果确实需要返回一个指针,则应该对其进行分配,或者返回一个仍然有效的指针。

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;
}

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

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