arrays - Segmentation fault in c dealing with scanf -
i'm writing program requires me union of 2 arrays. here code far. segmentation fault error after enter set a.
#include <stdio.h> void union(int a[], int b[], int set1, int set2) { int u[20], i, j, unionindex=0,trigger; for(i=0; i<set1; i++) { u[unionindex] = a[i]; unionindex++; } for(i=0; i<set2; i++) { trigger=0; for(j =0; j<set1; j++) { if(b[i] == u[j]) { trigger =1; break; } } if(trigger =0) { u[unionindex]=b[i]; unionindex++; } } for(i=0;i<unionindex;unionindex++) { printf(" %d",u[i]); } } int main(void) { int n=0; int m=0; int i; int j; printf("please enter number of elements in set a: "); scanf("%d",n ); int a[n]; printf("enter numbers in set: "); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("please enter number of elements in set b: "); scanf("%d",m ); int b[m]; printf("enter numbers in set: "); for(j=0;i<m;i++) { scanf("%d",&b[i]); } union(a,b,n,m); return 0; }
i'm pretty sure issue has arrays because program compile error right after user enters set a. i'm beginner @ c know lot more java, i'm thinking has memory allocation. i'm not sure how solve issue, if point me in right direction helpful.
you need pass address of variable scanf()
change
printf("please enter number of elements in set a: "); scanf("%d",n );
to
printf("please enter number of elements in set a: "); scanf("%d", &n);
same goes other place
printf("please enter number of elements in set b: "); scanf("%d", &m);
there possible mistake
its here
for(j =0; j<set1; j++) { if(b[i] == u[j])
in set1
equal n
, j
go 0 n-1
. , array u[]
has 20
elements. there possibility of array access out of bound if user enter value more 20
n
.
Comments
Post a Comment