Returning the minimum of a vector

Jan 27, 2012 at 2:00am

Hello all.

I have the two functions below and their corresponding main function.

Function 1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int maxofVec(int myarr[])
{
    size_t len=sizeof(myarr)/sizeof(myarr[0]);
    int minV=myarr[0];
    for(int i=1;i<len;i++)
    {
        if(myarr[i]<minV)
           {minV=myarr[i];}
    }

   return minV;
}

int main()
{
    int myarray[]={12,4,5,90,10,3,40,10,10,2,1,101,10};
    cout<<"\nThe minimum of the above is :"<<maxofVec(myarray);
    return 0;
}


Function 2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int maxofVec(int myarr[], int len)
{

    int minV=myarr[0];
    for(int i=1;i<len;i++)
    {
        if(myarr[i]<minV)
           {minV=myarr[i];}
    }

   return minV;
}



int main()
{
    int myarray[]={12,4,5,90,10,3,40,10,10,2,1,101,10};
    int len=(int)sizeof(myarray)/sizeof(myarray[0]);
    cout<<"\nThe minimum of the above is :"<<maxofVec(myarray,len);
    return 0;
}


Function 1 is returning the first array element, instead of the minimum element, while function 2 gives the minimum as expected. What could be wrong with function 1, is anything wrong with my use of sizeof().

The kind response of the vets will be appreciated.
Jan 27, 2012 at 2:15am
What could be wrong with function 1, is anything wrong with my use of sizeof().

Essentially, yes. When you pass an array into a function, its type changes. In main(), myarray is of type int[] or "array of int", so the sizeof operator will return the total size of all its elements in bytes. When that array gets passed into maxOfVec, its type becomes int* or "pointer to int", despite that the function's signature would suggest otherwise.

The first function is returning the first element because len is evaluating to 1 since sizeof(myarr) would be the size of one pointer (probably 4 bytes on your system). Passing in the length would be the correct approach in this case.

Also, this example doesn't use a "vector" though using one would reduce some complexity here (you could ask a std::vector for its size directly).
Last edited on Jan 27, 2012 at 2:24am
Jan 27, 2012 at 3:07am
Thank you and well said @shacktar.
Topic archived. No new replies allowed.