2015-01-05 3 views
1

C Программа вылетает после последнего скан/последнего цикла (игра с пустяками).C Сбой программы после последнего ввода

struct myQuiz*quizInput(int *nrQ) 
{ 
    int i, nrofrecords = 0; 
    struct myQuiz *Quiz = (struct myQuiz*)malloc(sizeof (struct myQuiz)**nrQ); 

    printf("How many Questions?\n"); 
    scanf_s("%d", nrQ); 

    for (i = 0; i < *nrQ; i++) //for-loop för att skriva in påståenden 
    { 
     printf("Trivia input: "); 
     fflush(stdin); 
     fgets(Quiz[i].qQuest, 100, stdin); 
     nrofrecords = nrofrecords + 1; 
     fflush(stdin); 

     printf("Enter answer '1'(yes) or '0' (no): "); 
     scanf_s("%d", &Quiz[i].qAns); 
     fflush(stdin); 

     printf("Enter the difficulty (1-5)?: "); 
     scanf_s("%d", &Quiz[i].qDiff); 


    } 
    return Quiz; 
} 
+1

удалить 'fflush (stdin)' это неопределенное поведение, что бы он сделал в любом случае? Вам нужно разместить больше кода, например, определение 'struct'. –

+3

Выполнение 'struct myQuiz * Quiz = (struct myQuiz *) malloc (sizeof (struct myQuiz) ** nrQ);' after' scanf_s ("% d", nrQ); ' – chux

+0

: эта строка: 'struct myQuiz * Quiz = (struct myQuiz *) malloc (sizeof (struct myQuiz) ** nrQ); ' 1) позволяет решить проблему, связанную с извлечением максимального размера токена. Предложить: 'struct myQuiz * Quiz = malloc (sizeof (struct myQuiz) * (* nrQ));' Обратите внимание на парсеры, чтобы отделить токен умножения от токена разыменования. 2) возвращаемое значение из malloc (и семейства) не должно быть отлито 3) возвращаемое значение всегда должно быть проверено, чтобы гарантировать, что распределение памяти было успешным. – user3629249

ответ

0

Вы должны инициализировать *nrQ первый

struct myQuiz*quizInput(int *nrQ) 
{ 
    int i, nrofrecords = 0; 
    struct myQuiz *Quiz; // = malloc(sizeof (struct myQuiz)**nrQ); you need to initialize *nrQ first 

    printf("How many Questions?\n"); 
    scanf_s("%d", nrQ); 

    Quiz = malloc(sizeof (struct myQuiz)**nrQ); 
    for (i = 0; i < *nrQ; i++) //for-loop för att skriva in påståenden 
    { 
     printf("Trivia input: "); 

     fgets(Quiz[i].qQuest, 100, stdin); 
     nrofrecords = nrofrecords + 1; 

     printf("Enter answer '1'(yes) or '0' (no): "); 
     scanf_s("%d", &Quiz[i].qAns); 

     printf("Enter the difficulty (1-5)?: "); 
     scanf_s("%d", &Quiz[i].qDiff); 
    } 
    return Quiz; 
}  

Также

  1. Не отвергни malloc
  2. Не fflush(stdin)
+0

смешивание 'fgets()' с 'scanf_s («% d »' этот путь не будет работать. Слева над '' \ n''' после прочтения числа. – chux

2

nRQ является входным сигналом для функции и памяти, выделенной на основе этого значения

struct myQuiz *Quiz = (struct myQuiz*)malloc(sizeof (struct myQuiz)**nrQ); 

Фактическое значение вопросы просят после таНоса, так что, если начальное значение передается функции меньше вопросов, происходит повреждение памяти. вам нужно сначала ввести вход, а затем выделить память позже.

printf("How many Questions?\n"); 
scanf_s("%d", nrQ); 
1
the code is using some trash from nrQ for the malloc 
before nrQ variable is set. 

returned values from I/O statements 
must be checked to assure successful operation. 

the user prompts fail to clearly indicate what the user is to input 

suggest: 

    printf("Please indicate how many Questions you will enter?\n"); 
    if(1 != scanf_s("%d", nrQ)) 
    { // then, scanf_s failed 
     perror("scanf_s for number questions failed"); 
     return(NULL); 
    } 

    // implied else, scanf_s successful 

    struct myQuiz *Quiz = NULL; 
    if(NULL == (Quiz = malloc(sizeof (struct myQuiz)*(*nrQ))))) 
    { // then, malloc failed 
     perror("malloc array of struct myQuiz failed"); 
     return(NULL); 
    } 

    // implied else, malloc successful 

    printf("\nNote: max question length: %d\n", sizeof(struct myQuiz.qQuest)); 
Смежные вопросы