简体   繁体   中英

I would like to pass an array from my main method to my function(min) so that the minimum can be calculated in the function(min)

#include <stdio.h>

int min(int pArray[], int nrOfArrayElements)
{
    min = pArray[0];
    for (int i = 1; i < nrOfArrayElements; i++)
    {
        if (pArray[i] < min)
        {
            min = pArray[i];
        }
    }
    return min;
}

int main()
{
    int x[10] = { 2,3,4,5,1,6,9,8,7,0 };
    int sizeOfArray, sizeOfElement, nrOfArrayElements;

    sizeOfArray = sizeOf(x);
    sizeOfElement = sizeOf(x[0]);
    nrOfArrayElements = sizeOfArray / sizeOfElement;
    int min = min(x[10],nrOfArrayElements);
    printf("smallest Array = %d", min);
    return 0;
}

The following errors appear whilst trying to pass my array from main to my function min im not quite sure why pArray[0] is classified as a pointer when I am just trying to get the element on that position.

main.c:13:9: error: lvalue required as left operand of assignment min = pArray[0];

main.c:19:8: error: lvalue required as left operand of assignment min = pArray[i];

main.c:32:16: error: called object 'min' is not a function or function pointer int min = min(x[10],nrOfArrayElements);

You have 3 problems.

  1. You are calling function sizeOf , while the actual name is sizeof . (Note the Capitalization)

  2. You are using an integer min and also a function min . Both identifiers cannot have the same name. I have changed the integer to min2 .

  3. In the function call to min , you are calling it with min(x[10],nrOfArrayElements) . Since the first parameter is an array of int, you need to pass the base address of the array, ie min(x,nrOfArrayElements)

Final code is below.

int min(int pArray[], int nrOfArrayElements)
{
    int min2;
    min2 = pArray[0];
    for (int i = 1; i < nrOfArrayElements; i++)
    {
        if (pArray[i] < min2)
        {
            min2 = pArray[i];
        }
    }
    return min2;
}

int main()
{
    int x[10] = { 2,3,4,5,1,6,9,8,7,0 };
    int sizeOfArray, sizeOfElement, nrOfArrayElements;
    sizeOfArray = sizeof(x);
    sizeOfElement = sizeof(x[0]);
    nrOfArrayElements = sizeOfArray / sizeOfElement;
    int min2 = min(x,nrOfArrayElements);
    printf("smallest Array = %d", min2);
    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