Reputation: 438
I keep getting a Segmentation Fault error when I run the program with a txt files with 5 numbers. First number is 5 (size of array) and then 0 1 2 3 4 It compiles just fine when I gcc -c *.c.
Main file
#include <stdio.h>
#include <stdlib.h>
#include "my.h"
int main(int argc, char *argv[])
{
char* file = argv[1];
int n;
int* a;
int i,j;
FILE *fp;
fp = fopen(file, "r"); // open file
fscanf(fp, "%d", &n); //scans for the first value for n
a = calloc(n, sizeof (int));
int num;
for (i =0; i<n - 1; i++) //stores and reads value
{
fscanf(fp, "%d", &num);
a[i] = num;
}
fclose(fp);
int* b;
b = f(a, n);
displayValue(b);
return 0;
}
Functions
#include <stdio.h>
#include <stdlib.h>
#include "my.h"
int* f(int* a, int n)
{
//odd-even sort
int h,j, c;
for ( h = 0; h < n - 1; h++)
{
if(a[h]%2==0)
{
if (a[h] > a[h + 1])
{
int temp = a[h];
a[h] = a[h +1];
a[h + 1] = temp;
}
}
}
for (j = 0; j < n - 1; j++)
{
if(a[j]%2!=0)
if (a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j +1];
a[j + 1] = temp;
}
}
return a;
}
void displayValue(int* b)
{
int index = 0;
while (0 == 0)
{
printf("Enter the index: ");
scanf("%d", &index);
if (index == -1)
exit(0);
else
printf("%s", &b[index]);
}
}
Header
int main(int argc, char *argv[]);
int* my(int* a, int n);
void displayValue(int* b);
Upvotes: 0
Views: 143
Reputation: 197
C is dangerous. Anything that can go wrong will go wrong.
Always check the return values of function calls, and handle possible failures.
Each of the standard library function calls has a man
page (if you have trouble finding it, use man -a <function>
). The man
pages document the possible return values and their meanings. man
is your fried, get used to studying it; it is a valuable resource.
Beware of conditions that result in "undefined behavior".
Upvotes: 3