Click here to Skip to main content
15,891,976 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here there is segmentation fault here, why?

What I have tried:

C++
#include<stdio.h>
int findmid(int [],int);
int main()
{
    int n,c,i;
    int a[n];
    printf("Enter the valu of n :");
    scanf("%d",&n);
    int x;
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
    x=sizeof(a)/sizeof(int);
    c=findmid(a,x);
    printf("%d",c);
    return 0;
}

int findmid(int a[],int x)
{
    return a[x/2];
}                              
Posted
Updated 10-May-21 3:42am

See my answer to your previous question: Size of an array in the programme[^]
 
Share this answer
 
See also my answer to your previous question: Size of an array in the programme[^]
:D
 
Share this answer
 
Quote:
Why I am getting segmentation fault error here?

Because your code is wrong
C++
#include<stdio.h>
int findmid(int [],int);
int main()
{
    int n,c,i;
    int a[n]; // you can't allocate an array dynamically sized at runtime
    printf("Enter the valu of n :");
    scanf("%d",&n); // before knowing the size
    int x;
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
    x=sizeof(a)/sizeof(int);
    c=findmid(a,x);
    printf("%d",c);
    return 0;
}

int findmid(int a[],int x)
{
    return a[x/2];
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900