I have a question! It's going to be easy, but please take a look! EXC_BAD_ACCESS

Asked 2 years ago, Updated 2 years ago, 39 views

#include <stdio.h>

int main(void) {
    int aList[5] = {40, 20, 30, 40, 50};
    int nMax = aList[0];

    for(int i=0; aList[i] != '\n'; i++) {
        if(nMax < aList[i]) nMax = aList[i];
    }

    printf("MAX: %d\n", nMax);
}

Hello! I'm Corinne, who is studying C new!

I was studying the arrangement and there was an error in the for statement here!

(I'm trying to get the maximum number in the array!))

Thread 1: EXC_BAD_ACCESS (code=1, address=0x7ffeefc00000) 

That's what they say.

aList[i]!= '\n' I think it's because of this part, but I don't know why it's an error. You can just say (i<5) but I'm trying to make it a little better, so please tell me why it's wrong.

c array

2022-09-20 20:18

1 Answers

i<5 becomes false when i becomes 5. So, it goes up to four and it's over.

aList[i]!= '\n' continues to be true no matter how i increases. i will continue to increase. aList is only available up to aList[4] and nothing more. So, in the debug build, it becomes aList[5] and as soon as you try to read it, it approached the size of the specified array, so the error BAD_ACCESS would have occurred.


2022-09-20 20:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.