skip to Main Content

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:%cn", (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

2

Answers


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

    for( k=0; k < sizeof right_choices; k++) {
        scanf(" %c", &right_choices[k]);
    }
    
    Login or Signup to reply.
  2. 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]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search