What are pointers to pointers good for?

后端 未结 5 1637
难免孤独
难免孤独 2021-02-04 10:01

In the Go programming language; how can pointers to pointers become useful?

(Why are they not illegal if they are not really useful?)

5条回答
  •  时光取名叫无心
    2021-02-04 10:50

    In C pointers to pointers are quite common. For example:

    • more dimensional arrays (for example an array of strings, char** argv might be the most prominent example here)
    • pointers as output parameters

    In Go however, pointers to pointers are quite rare. Instead of accessing arrays by a pointer, there is a slice type (which also stores a pointer internally). So, you still might get the same kind of indirection by using a slice of slices in Go, but you normally won't see something like **int here.

    The second example however might still apply to Go programs. Let's say you have a function which should be able to change a pointer passed as parameter. In that case, you will have to pass a pointer to that pointer, so that you can change the original pointer. That's extremely common in C, because functions can only return one value (which is often some kind of error code) and if you want to return an additional pointer, you will have to use a pointer to that pointer as output parameter. A function in Go however, can return multiple values, so the occurrences of pointers to pointers are also rare. But they might still be useful and might lead to a nicer API in some cases.

    For example, the atomic.StorePointer function might be one of those rare but well hidden use-cases for pointers to pointers in the standard library.

提交回复
热议问题