简体   繁体   中英

trying to print largest value of the array..but printing garbage

Hey i am trying to print largest element in an array using function and pointers. Below is my code but its printing garbage value. Please help.

void findmax(int arr[],int,int*);
void findMax(int arr[], int n, int* pToMax)
{
    if (n <= 0) 
        return;      // no items, no maximum!

int max = arr[0];
pToMax = &arr[0];

for (int i = 1; i < n; i++)
{
    if (arr[i] > max)
    {
         max = arr[i];
         pToMax = (arr+i);
    }
}
}       
int main()
{
    int nums[4] = { 5, 3, 15, 6 };
    int *ptr;
    findMax(nums, 4, ptr);
    printf("The maximum is at address %u\n", ptr);
    printf("It's at index %d\n",ptr - nums);
    printf("Its value is %d\n", *ptr);
}

With int *pToMax in findMax(int arr[], int n, int* pToMax) and

calling as findMax(nums, 4, ptr); you just pass ptr as a value.

The updated value won't be reflected after function exits.

You need to use **pToMax

to save address.

void findMax(int arr[], int n, int** pToMax)
{
    if (n <= 0) 
        return;      // no items, no maximum!

int max = arr[0];
*pToMax = &arr[0]; //Store base address

for (int i = 1; i < n; i++)
{
    if (arr[i] > max)
    {
         max = arr[i];
         *pToMax = (arr+i); //Store max address
    }
}

}

call using

findMax(nums, 4, &ptr);

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