Reputation: 7
I am a beginner in programming. What is a segmentation fault and how to remove that on the following program?
The following is a compare the triplets problem asked in hackerrank. I receive a segmentation fault when attempting to run the program.
int main() {
int a, b, c;
c = points(a, b);
printf("%d", c);
return 0;
}
int points(int a[10], int b[10]) {
int p = 0, q = 0;
for (int i = 0; i < 3; i++) {
printf("%d", a[i]);
scanf("%d", & a[i]);
}
for (int j = 0; j < 3; j++) {
printf("%d", b[j]);
scanf("%d", & b[j]);
}
for (int k = 0; k < 3; k++) {
if (a[k] > b[k]) {
++p;
return p;
} else {
if (a[k] = b[k])
++q;
return q;
}
}
return 0;
}
Upvotes: 0
Views: 134
Reputation: 59
int a,b,c;
c=points(a,b);
You are passing arguments to function without setting theirs value. Remember that in C, you are passing arguments to function by value.
int points(int a[10],int b[10])
This function expects two arrays of ten integers. You are passing only one integer for each.
You should also read about passing array arguments to function (if that was your intention). In C, You can't pass whole array to function unless it is wraped into a struct. You should only pass address of the first array element and in some way define size. For example:
#define ARRAY_SIZE 10
int foo(int tab[])
{
int i;
for (i = 0; i < ARRAY_SIZE; i++)
tab[i] = do_stuff();
}
int main(void)
{
int tab[ARRAY_SIZE];
foo(tab);
}
You can also not define ARRAY_SIZE macro, but pass another argument to a function which will define the size of passed array.
Upvotes: 3