Search code examples
cintscanfcalculatorexc-bad-access

Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT) is causing my scanf to fail


#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main(int argc, const char * argv[]) {
    bool isTrue=true;
    int nums[50];
    for (int i = 0; i<sizeof(nums); i++) {
        nums[i]=2147483647;
    }
    char operations[49];
    int counter = 0;
    printf("What is your first number? (THERE IS NO PEMDAS, THE NUMBER 2147483647 is not allowed)\n");
    scanf("%d", &nums[counter]); // Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
}

I have more code, but it is unrelated to the problem. Thank you for helping and just ask if more info is needed (I am making a calculator that lines up inputs and calcultes them eg. 3 + 5 * 9 / 2 = 36. The equation can have at most 50 integers and 49 operations.)


Solution

  • You're taking the size of your array in bytes, not in the number of elements. Do this instead:

    for( int i = 0; i < sizeof(nums) / sizeof(nums[0]); i++ )
    {