c - what the difference between a function and *function? -
i confused in c newbie. know 1.1 giving me maximum value , 1.2 giving me maximum value variable address [picture]. my question how 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 %d @ index %x",max,&max); return &max; }
the *
in function definition not function pointer, it's function's return type. findmax
function returns pointer integer. call other functions in main:
int a[] = {1,2,3,4}; int *p = findmax(a, 4);
there problem, in findmax
function, returned pointer local variable, storage of variable no longer available when function returns. use causes undefined behavior. can return max integer instead, if need return pointer, should allocate it, or return pointer 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; }
Comments
Post a Comment