Home > Mobile >  Program stops working and it says zsh abort
Program stops working and it says zsh abort

Time:11-19

So here is my code

#include<math.h>
#include<stdio.h>
#include"hw1.h"

int main (int argc, char *argv[]) {
    int num_choices, k; 
    char right_choices[20];
    
    do {
        printf("Enter number of choices:\n");
        scanf("%d", &num_choices);
    }
    while ((num_choices > 26) || (num_choices < 1));

    num_choices = num_choices - 1   'A';
    printf("Max choice:%c\n", (char)num_choices);

    printf("Enter answer key:\n");
        for( k=1; k < 20; k  )
        scanf(" %c", &right_choices[20]);


    return 0;
}

while compiling everything seems ok. While running the second scanf is supposed to run 20 times but everytime it stops at 19 and it says : "zsh abort"

I tried doing it 10 times to see if that was the problem but the same message appeared at the 9th time. It always stops at n-1.

The same code runs on linux perfectly.

Thank you very much!

i searched up the problem but i didnt find any usefull information

CodePudding user response:

Arrays in almost all languages work in the same way. when you create foo[20], that means your array looks like [0][1]...[18][19].

The element right_choices[20] doesn't exist, it should be right_choices[k]

CodePudding user response:

C is a 0-indexed language, change your loop to

for( k=0; k < sizeof right_choices; k  ) {
    scanf(" %c", &right_choices[k]);
}
  • Related