Why use double indirection? or Why use pointers to pointers?

前端 未结 18 2221
失恋的感觉
失恋的感觉 2020-11-22 10:37

When should a double indirection be used in C? Can anyone explain with a example?

What I know is that a double indirection is a pointer to a pointer. Why would I ne

18条回答
  •  攒了一身酷
    2020-11-22 11:31

    For instance if you want random access to noncontiguous data.

    p -> [p0, p1, p2, ...]  
    p0 -> data1
    p1 -> data2
    

    -- in C

    T ** p = (T **) malloc(sizeof(T*) * n);
    p[0] = (T*) malloc(sizeof(T));
    p[1] = (T*) malloc(sizeof(T));
    

    You store a pointer p that points to an array of pointers. Each pointer points to a piece of data.

    If sizeof(T) is big it may not be possible to allocate a contiguous block (ie using malloc) of sizeof(T) * n bytes.

提交回复
热议问题