它编译但崩溃与exc_bad_access

时间:2015-07-08 02:35:39

标签: c++ pointers memory file-io

程序编译但崩溃

fscanf ( fileHandle, "%d", &numberPeople );

我认为它与内存分配有关或文件指针超出范围然后指向错误的位置。

这些只是基于编译器错误的猜测:

Thread 1: exc_bad_access(code=1, address=0x68)

#include <stdio.h>
#include <iostream>

//salesman struct
struct Salesman
{
    char firstname[64];
    char lastname[64];
    char middleinitial[1];
    int averagecents;
    int totalcents;
};

void calculateAveragesTotals(FILE*, int, int, int, int);
void tableWriter(int, int, int, int);

int main(int argc, const char * argv[]) {

    //setup variables
    const char* inputFilename = "TheSales.txt";
    int numberPeople = 0, weeksToHandlePerPerson = 0;
    int workweeklength = 5;
    int totalcents = 0;

    //open file
    FILE* fileHandle = fopen ( inputFilename, "r" );
    fscanf ( fileHandle, "%d", &numberPeople );
    fscanf ( fileHandle, "%d", &weeksToHandlePerPerson );

   calculateAveragesTotals(fileHandle, numberPeople, weeksToHandlePerPerson, workweeklength, totalcents);

    int averagecents = totalcents / ( numberPeople * weeksToHandlePerPerson );

    std::cout << "total for all: " << totalcents / 100 << "." << totalcents % 100 << " and     average for all $" <<
    averagecents / 100 << "." << averagecents % 100 << std::endl;

}


 void calculateAveragesTotals(FILE* fileHandle, int numberPeople, int weeksToHandle, int workweeklength, int totalcents) {
    //do calculations
    for ( int i = 0; i < numberPeople; ++i )
    {
        Salesman nextsalesman;
        fscanf ( fileHandle, "%s", nextsalesman.firstname );
        fscanf ( fileHandle, "%s", nextsalesman.middleinitial );
        fscanf ( fileHandle, "%s", nextsalesman.lastname );

        float t1, t2, t3, t4, t5;
        fscanf ( fileHandle, "%f %f %f %f %f", &t1, &t2, &t3, &t4, &t5 );

        nextsalesman.totalcents = 100 * ( t1 + t2 + t3 + t4 + t5 );
        nextsalesman.averagecents = nextsalesman.totalcents / workweeklength;
        totalcents += nextsalesman.totalcents;

        //print calculations calculateNumbers()
        std::cout << "salesman " << i << " total: $" << nextsalesman.totalcents / 100 << "." <<     nextsalesman.totalcents % 100
        << " and average $" << nextsalesman.averagecents / 100 << "." << nextsalesman.averagecents % 100 << std::endl;

    }
 }

0 个答案:

没有答案