문제

When allocating and then attempting to access an array of pointers to pointers:

void tester(char ***p)
{
    int i;
    char **pp;

    pp = *p;
    pp = calloc(10, sizeof(*pp));

    for (i = 0; i < 10; i++)
        printf("%d = %p\n", i, pp[i]);

            *p = pp;
}

void tester_broken(char ***p)
{
    int i;

    *p = calloc(10, sizeof(**p));

    for (i = 0; i < 10; i++)
        printf("%d = %p\n", i, *p[i]);
}

int main(void)
{ 
    char **a;

    tester(&a);
    tester_broken(&a);

    return 0;
}

Can anyone explain why one of these works and the other seg faults?

도움이 되었습니까?

해결책

It's a precedence problem. Try:

void tester_fixed(char ***p)
{
    int i;

    *p = calloc(10, sizeof(**p));

    for (i = 0; i < 10; i++)
        printf("%d = %p\n", i, (*p)[i]);
}

The bracket operator (array subscripting) binds tighter than the asterisk operator (dereference). The parentheses make your intent explict.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top