6/5/2023 0 Comments Multiple indirection.![]() ![]() One approach is to declare a pointer to a pointer, then allocate an array of pointers to it: T **arr // arr will point to an NxM array of TĪrr = malloc( sizeof *arr * n ) // allocate N objects of type T *Īrr = malloc( sizeof *arr * m ) // allocate M objects of type T Suppose you want to allocate an Nx M array of T, but you don't know the values of N or M at compile time. The semantics are the same in all three cases we write a new value to var through the expression *ptr it's just the type of var is a pointer type, meaning the type of ptr must be a pointer type with one more level of indirection.īuilding an N-dimensional array by pieces You could replace Q with R *, giving void foo( R ***ptr ) Again, both *ptr and var refer to the same memory location, but this time, var contains a pointer value. In this second case, you want to modify the pointer value stored in var. If T is a pointer type Q *, then you wind up with a pointer to a pointer: void foo( Q **ptr ) The expression *ptr in foo refers to the same object in memory as var in bar, so writing to *ptr is equivalent to writing to var. *ptr = new_value() // writes new value to thing pointed to by ptr Multiple indirection generally occurs in the following scenarios: writing to a parameter of pointer type, and building an N-dimensional array by pieces.įor any function parameter of type T, if you want the function to modify the value of the parameter and have that new value reflected in the caller, you must pass a pointer: void foo( T *ptr ) There is an excellent example with diagrams and code here. And I'm sure there are others I've missed. Although they all seem to use the same construct, in reality the underlying purpose is quite different. It's important to keep these conceptually separate. It's basically impossible to insert an item into a linked list without them. Manipulating a structure that itself contains pointers, such as linked lists, trees and so on.A 'handle' for a memory block, so the owner of the block can move it without the user of the block needing to know.The data will usually be allocated with malloc(). 'Jagged' or N-dimensional arrays, stored as array of pointer to data.The argc argument to main looks like that. ![]() Accessing an array of C null-terminated strings each string is itself a pointer.As an output argument of a function call, pass a pointer to the pointer you want output or modified.There are a surprising number of situations in which you need to use one of these beasties. You dereference it twice to get to the final typed value. A pointer-to-pointer simply means that you have an address of a memory location where some other pointer is stored. ![]()
0 Comments
Leave a Reply. |