0

I want to find the largest element in an array using call by reference method that is functions and pointers. I am getting an error at function call. Here is my try:

#include <stdio.h>
void bigg(int *a[10],int *N);

int main()
{
    int a[10],i,N,p;
    printf("Enter the total number of elements in the array:\n");
    scanf("%d",&N);
    printf("Enter the elements in the array one by one:\n");
    for(i=0;i<N;i++)
    {
        scanf("%d",&a[i]);
    }
    bigg(&a,&N);    
}

void bigg(int *a[10],int *N)
{
    int i,max;
    
    max = *a[0];
    
    for(i=0;i<*N;i++)
    {
        if( *a[i] > max)
        {
            max = *a[i];
        }
    }
    printf("The biggest element in the given array is: %d",max);    
}

1
  • Consider checking the value of N received from the input. You allocated enough memory only for 10 int's, therefore N should be equal or less than that. Commented Jan 11, 2021 at 4:22

2 Answers 2

1

Your basics of pointer is not clear. For this question it works.

#include <stdio.h>
void bigg(int a[],int *N);

int main()
{
    int a[10],i,N,p;
    printf("Enter the total number of elements in the array:\n");
    scanf("%d",&N);
    printf("Enter the elements in the array one by one:\n");
    for(i=0;i<N;i++)
    {
        scanf("%d",&a[i]);
    }
    bigg(a,&N);    
}

void bigg(int a[],int *N)
{
    int i,max;
    
    max = a[0];
    
    for(i=0;i<*N;i++)
    {
        if( a[i] > max)
        {
            max = a[i];
        }
    }
    printf("The biggest element in the given array is: %d",max);    
}

Sign up to request clarification or add additional context in comments.

2 Comments

It's also good to clarify what changes have you made in the code.
Thank You very much sir. I got my mistake and now I am able to solve the problem.
1

What you're passing doesn't match the expected argument.

The function bigg is expecting for it's first argument an int *[10] which is an array of pointers. You're passing it &a which is a pointer to an array and has type int (*)[10].

You actually don't want either of these. An array name is, in most contexts, converted to a pointer to its first element. So if you pass that you'll have access to the elements. So change your function definition to accept an int * for the first argument (and an int for the second since you're not changing N):

void bigg(int *a, int N)
{
    int i,max;
    
    max = a[0];
    
    for(i=0;i<N;i++)
    {
        if( a[i] > max)
        {
            max = a[i];
        }
    }
    printf("The biggest element in the given array is: %d",max);    
}

And call it like this:

bigg(a,N);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.