Segfault when trying to index pointer to pointers in function

后端 未结 2 1743
礼貌的吻别
礼貌的吻别 2021-01-28 17:54

I\'m trying to do something with an array (malloc-ed), namely arr of a custom struct. The array is passed by reference to a function. I get a segfault whenever I tr

相关标签:
2条回答
  • 2021-01-28 18:50

    Your problem is the line

    (*arr[1])->i = 3;
    

    Because the subscripting operator's evaluation precedes the dereferencing's evaluation it is equivalent to the following:

    (*(arr[1]))->i = 3;
    

    This is obviously wrong. You need

    (*arr)[1]->i = 3;
    

    therefore.


    Notes:

    • do not cast the result of malloc
    • add #include <stdlib.h> to resolve the warning
    • adding an extra level of indirection (foo*** pointing to foo**) is unnecessary; just copy by value
    • (in addition to the upper note) a good old 1D array should actually be sufficient in your case

    • call free after malloc

    0 讨论(0)
  • 2021-01-28 18:50

    The warning you get is because you forgot to #include <stdlib.h>, so malloc is not declared, so the compiler assumes it should return int. This can lead to all kinds of fun problems. (And you should remove those casts.)


    The other problem is in this line: (*arr[1])->i = 3;

    Postfix operators (like []) bind tighter than prefix operators (like *), so *arr[1] parses as *(arr[1]).

    You can write (*arr)[1]->i instead to fix this, but as it turns out, your function never actually modifies *arr, so there's no reason to pass arr (the other arr, the one in main)'s address to it. Just do this:

    void doSomething(foo **arr)
    {
      arr[1]->i = 3;
    }
    

    and call it as doSomething(arr).

    0 讨论(0)
提交回复
热议问题