[ C ] Multi-pointer question! I know it's easy, but I don't understand. Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)

Asked 2 years ago, Updated 2 years ago, 47 views

#include <stdio.h>

int main() {

    char* astrList[3] = {"Hello", "World", "String"};
    char* *ppstrList = astrList;
    char** *pppstrList = &ppstrList;

    puts(*pppstrList[0]);
    puts(pppstrList[2][0]);

    return 0;
}

I am studying C by myself. In the last puts(), Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT) error occurred, but I don't know why.

I'm looking at a book, and in the example,

puts(* (*(pppstrList + 2) + 0 ) );

Can I change it like this? That's why I tried it. Why does this error come up?

-> The calculation result will be char* Then the string should come out well even if it's puts()...

c array pointer

2022-09-20 20:12

1 Answers

Probably puts (*(*(pppstrList+2)+0); is a typo of puts (*(*(pppstrList+0)+2));

Please refer to the code below. For your information, I added another code below.

#include <stdio.h>

int main() {

    const char* astrList[3] = { "Hello", "World", "String" };
    const char** ppstrList = astrList;
    const char*** pppstrList = &ppstrList;

    puts(*pppstrList[0]);

    puts(pppstrList[0][2]);
    puts(*(*(pppstrList + 0) + 2));

    return 0;
}

The code below is a slight change to the code above.

#include <stdio.h>

int main() {

    const char* astrList[3] = { "Hello", "World", "String" };
    const char* bstrList[3] = { "Hi", "Friend", "Good luck" };
    const char** ppstrList[2] = { astrList,bstrList };
    const char*** pppstrList = ppstrList;

    puts(*pppstrList[0]);

    puts(pppstrList[0][2]);
    puts(*(*(pppstrList + 0) + 2));

    puts(pppstrList[1][2]);

    return 0;
}


2022-09-20 20:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.