Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many levels of pointers can we have?

How many pointers (*) are allowed in a single variable?

Let's consider the following example.

int a = 10; int *p = &a; 

Similarly we can have

int **q = &p; int ***r = &q; 

and so on.

For example,

int ****************zz; 
like image 806
Parag Avatar asked Apr 10 '12 10:04

Parag


People also ask

How many pointer are there?

There are majorly four types of pointers, they are: Null Pointer. Void Pointer. Wild Pointer.

Can pointer be extended?

The concept of the pointer can be extended further. As we have seen earlier, a pointer variable can be assigned the address of an ordinary variable. Now, this variable itself could be another pointer. This means that a pointer can contain the address of another pointer.

How many levels of indirection can you have in a single declaration?

The answer depends on what you mean by "levels of pointers." If you mean "How many levels of indirection can you have in a single declaration?" the answer is "At least 12."


2 Answers

The C standard specifies the lower limit:

5.2.4.1 Translation limits

276 The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits: [...]

279 — 12 pointer, array, and function declarators (in any combinations) modifying an arithmetic, structure, union, or void type in a declaration

The upper limit is implementation specific.

like image 173
P.P Avatar answered Oct 07 '22 14:10

P.P


Actually, C programs commonly make use of infinite pointer indirection. One or two static levels are common. Triple indirection is rare. But infinite is very common.

Infinite pointer indirection is achieved with the help of a struct, of course, not with a direct declarator, which would be impossible. And a struct is needed so that you can include other data in this structure at the different levels where this can terminate.

struct list { struct list *next; ... }; 

now you can have list->next->next->next->...->next. This is really just multiple pointer indirections: *(*(..(*(*(*list).next).next).next...).next).next. And the .next is basically a noop when it's the first member of the structure, so we can imagine this as ***..***ptr.

There is really no limit on this because the links can be traversed with a loop rather than a giant expression like this, and moreover, the structure can easily be made circular.

Thus, in other words, linked lists may be the ultimate example of adding another level of indirection to solve a problem, since you're doing it dynamically with every push operation. :)

like image 24
Kaz Avatar answered Oct 07 '22 16:10

Kaz