Ошибка подтверждения отладки программирования C - PullRequest
0 голосов
/ 14 декабря 2011

Я делаю домашнее задание на C и пытаюсь запустить эту программу, но я получаю следующее:

http://i.imgur.com/UUdLB.png

Может кто-нибудь, пожалуйста, запустите это и посмотрите, получите ли вы то же самое? (Измените выходной каталог для текстовых файлов)

Я давно пытаюсь и просто не могу этого сделать:

Вот код:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

/////////////////
#define SIZE 2
/////////////////

struct Stock
{
    char name[10];
    int numShares;
    float buyShare,currPrice,fees;
    float initCost,currCost,profit;
};

/* Load the data from the keyboard and calculates 
the Initial Cost, Current Cost, and Profit 
for each stock via an array */

void load(struct Stock s[], int n) 
{
    char nameCompare[30] = "Open the bay doors";
    int i;
    for(i=0;i<n;i++)
    {
        printf("Enter the Stock Name\n");
        printf(">");
        gets(s[i].name);

        /////////////////////////////////////
        if(strncmp (s[i].name,nameCompare,10) == 0)
        {
            printf("\tI'm sorry, Dave, I'm afraid I can't do that\n");
            Sleep(3000);
            exit(1);
        }

        /////////////////////////////////////
        printf("Enter the Number of Shares\n");
        printf(">");
        scanf("%d", &s[i].numShares);
        printf("Enter the Buying Price Per Share\n");
        printf(">");
        scanf("%f", &s[i].buyShare);
        printf("Enter the Current Price Per Share\n");
        printf(">");
        scanf("%f", &s[i].currPrice);
        printf("Enter the Yearly Fees\n");
        printf(">");
        scanf("%f", &s[i].fees);

        s[i].initCost = (float)s[i].numShares * s[i].buyShare;
        s[i].currCost = (float)s[i].numShares * s[i].currPrice;
        s[i].profit = s[i].currCost - s[i].initCost - s[i].fees;
        fflush(stdin);
    }
}

/* Sort the array of structures 
on stock name and print the array 
after the sort is completed */

void sort(struct Stock s[], int n)
{
    Stock t;
    for(int i=0;i<n-1;i++)
        for(int j=0;j<n-1;j++)
            if(strcmp(s[j].name, s[j+1].name)>0)
            {
                t=s[j];
                s[j]=s[j+1];
                s[j+1]=t;
            }
}

/* Calculate and print the total profit for all of the stocks. 
That is, find the sum of the 5 profits for each stock. In 
addition, find and print out the number of stocks that 
had a positive profit, the number of stocks that had a 
negative profit, and the number of stocks that broke 
even, that is had a profit of $0.00 */

void calc(struct Stock s[],int n)
{
    float total=0;

    int Pos=0;
    int Neg=0;
    int Even=0;

    for(int i=0;i<n;i++)
    {
        total +=s[i].profit;
        if (s[i].profit>0)
            ++Pos;
        else if (s[i].profit<0)
            ++Neg;
        else
            ++Even;
    }

    printf("\n");
    printf("%d of stocks broke Positive\n",Pos);
    printf("\t%d of stocks broke Negative\n",Neg);
    printf("\t\t%d of stocks broke Even\n",Even);
    printf("\n");
    printf("The Total Trofit is $%f\n", total); //Check output
    printf("\n");
}
//Output of the calc function
void print(struct Stock s[], int n)
{
    for(int i=0;i<n;i++)
    {
        printf("\n");
        printf("The stock is %s\n", s[i].name);
        printf("\tWith Initial cost of $%0.2f\n", s[i].initCost);
        printf("\t\tCurrent cost is $%0.2f\n", s[i].currCost);
        printf("\t\t\tAnd your Profit is $%0.2f\n", s[i].profit); //Check output
        printf("\n");
    }
}
//Save the array of structures to a text file.
void savetext(struct Stock s[], int n)
{
    FILE *f;
    f = fopen("c:\\cs36\\textfile.txt","w"); 
    int i;
    for(i=0;i<n;i++)
    {
        fprintf(f,"%s\n",s[i].name);
        fprintf(f,"%d  %f  %f  %f  %f  %f  %f\n", s[i].numShares, s[i].buyShare, s[i].currPrice, s[i].fees, s[i].initCost, s[i].currCost, s[i].profit);
    }
    fclose(f);
}
//Retrieve and print the text file.
void loadtext(struct Stock s[], int n)
{
    FILE *f;
    f = fopen("c:\\cs36\\textfile.txt","r");
    for(int i=0;i<n;i++)
    {
        fgets(s[i].name, sizeof(s[i].name), f);
        fscanf(f, "%d%f%f%f%f%f%f\n", &s[i].numShares, &s[i].buyShare, &s[i].currPrice, &s[i].fees, &s[i].initCost, &s[i].currCost, &s[i].profit);
    }
    fclose(f);
}
//Save the array of structures to a binary file.
void savebin(struct Stock s[], int n)
{
    FILE *f;
    f = fopen("c:\\cs36\\binfile.bin","wb");
    if(! f)
    { 
        printf("Could not open the file");
        exit(1); 
    }
    else
        fwrite(&s, sizeof(s[10]), n, f);
    fclose(f);
}
//Retrieve and print the binary file.
void loadbin(struct Stock s[], int n)
{
    FILE *f;
    f = fopen("c:\\cs36\\binfile.bin","rb");
    if (! f)
    { 
        printf("Could not open the file");
        exit(1); 
    }
    else
        fread(&s, sizeof(s[10]), n, f);
    fclose(f);
}

int main (void)
{
    printf("Hello, Dave\n");
    Stock s[SIZE];
    load (s, SIZE);
    sort (s, SIZE);
    savetext (s, SIZE);
    savebin (s, SIZE);
    print (s, SIZE);
    calc (s, SIZE);
    loadtext (s, SIZE);
    print (s, SIZE);
    loadbin (s, SIZE);
    print (s, SIZE);
    system("PAUSE");
}

Это C, использующий Visual C ++ 2008 Express

Ответы [ 3 ]

3 голосов
/ 14 декабря 2011

Вы передали указатель NULL где-то в вызове на printf.Скорее всего, это строка формата или строковый аргумент (%s).

Нажмите кнопку отладки, и визуальный отладчик покажет вам точно, где в вашем коде происходит ошибочный вызов.

2 голосов
/ 14 декабря 2011

Я заметил четыре основные проблемы:

  • вы смешиваете scanf и gets. gets в частности, это яма, потому что она переполняет буферы без раскаяния. Обычно лучше выбрать один или другой. Я обнаружил, что наиболее надежным является использование fgets для сканирования каждой строки в статический буфер и анализа оттуда.

  • вы звоните fflush(stdin). Хотя сброс потока четко определен для выходных потоков, он не для ввода; скорее всего, эта линия не делает то, что вы ожидаете.

  • вы компилируете c с помощью компилятора c ++. В результате вы создали код, который никуда не вписывается. В частности, вы сокращаете struct Stock до Stock, но никогда typedef struct Stock Stock; Вы также используете циклы for в стиле C ++ и C99, что не так уж и сложно, но gcc (компилятор linux) будет жаловаться, пока накормить его флагами.

И государственный переворот! В настоящее время вы читаете и пишете свои двоичные файлы примерно так:

 fwrite(&s, sizeof(s[10]), n, f);
 fread(&s, sizeof(s[10]), n, f);

Проблема в том, что массив, передаваемый в качестве параметра функции, рассматривается как указатель, а не как массив. Таким образом, &s дал вам местоположение указателя, а не адрес массива. fread затем разбил ваш стек содержимым двоичного файла. Изменение этих строк на

fwrite(s, sizeof(*s), n, f); 
fread(s, sizeof(*s), n, f);

исправляет основную проблему.

При работе с массивами вы редко обнаруживаете, что берете их адрес, потому что они затухают в любом случае на указатель на свой первый элемент.

1 голос
/ 14 декабря 2011

Вы пытаетесь получить доступ к нулевому указателю. Так что он выдаст эту ошибку.

    fprintf(f,"%s\n",s[i].name);

В этих строках s [i] может быть нулевым для некоторых случаев в вашей программе, поэтому вы пытаетесьчтобы получить доступ к переменной-члену объекта, которая имеет значение NULL.

Так что только она выдает эту ошибку времени выполнения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...