Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22176

How do I fix the segmentation fault error in C

$
0
0

I am new to C and I can't figure it out. The code compiles and lets me run it one time but when I enter it gives me segmentation fault. I ran gdb and backtraced it to find that the segmentation fault was in int main () in commissionOfAMechanic (name, &percent); but I don't know how to make it work. If someone could give me any types of suggestions to fix that error. The files I used in the code are in the bottom.

#include <stdio.h> #include <string.h>#include <assert.h>#include <stdlib.h>void commissionOfAMechanic (char *mechanicName, int *comm){    FILE * fp = fopen ("NameCommissions.txt", "r");    if ( fp == NULL )    {        printf ( "Unable to open the file\n" );        exit (-1);    }    char temp [16];    int commission;    int i;    for ( i = 0 ; i < 4 ; i++ )    {        fscanf ( fp, "%s %d", temp, *comm);        if (temp, *mechanicName)            break;    }    fclose (fp);    printf ( "The name given is %s and his commission is %d \n", temp, *comm );}void priceOfAllServices ( float pr[]){    FILE * fp = fopen ( "PriceOfServices.txt", "r");    if (!fp)    {        printf ( "Can't open file.\n");        exit (-1);    }    char temp [16];    fscanf (fp, "%s %d", temp, &pr[0]);    fscanf (fp, "%s %d", temp, &pr[1]);    fscanf (fp, "%s %d", temp, &pr[2]);    fscanf (fp, "%s %d", temp, &pr[3]);    fclose (fp);}void getWeeklyStatsOfaMechanic (char *name, int jobs[]){    FILE * fp = fopen ("JobsDone.txt", "r");    if (! fp)    {        printf ("Can't open file.\n");        exit (-1);    }    char temp [16];    fscanf (fp, "%s %d", temp, &jobs[0]);    fscanf (fp, "%s %d", temp, &jobs[1]);    fscanf (fp, "%s %d", temp, &jobs[2]);    fscanf (fp, "%s %d", temp, &jobs[3]);    int i;    for ( i = 0 ; i < 4 ; i++ )    {        fscanf (fp, "%s%d%d%d%d", temp, jobs[0], jobs[1], jobs[2], jobs[3]);        if (strcmp (temp, name ))        {            break;        }    }    printf ( "Jobs done by %s %d %d %d %d \n", temp, jobs[0], jobs[1], jobs[2], jobs[3]);    fclose (fp);}int main (){    int percent;    char name[16];    int jobs[4];    float prices[4];    printf ( "Please enter the name of the Mechanic\n");    scanf ("%s", name);    commissionOfAMechanic (name, &percent);    priceOfAllServices (prices);    getWeeklyStatsOfaMechanic (name, jobs);    float total = jobs[0]*prices[0] +                  jobs[1]*prices[1] +                  jobs[2]*prices[2] +                  jobs[3]*prices[3];    printf ( "Name = %s Total Commission = %.2f\n", name, total);    return 0;}

enter image description here


Viewing all articles
Browse latest Browse all 22176

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>