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;

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.


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. :)


Theoretically:

You can have as many levels of indirections as you want.

Practically:

Of course, nothing that consumes memory can be indefinite, there will be limitations due to resources available on the host environment. So practically there is a maximum limit to what an implementation can support and the implementation shall document it appropriately. So in all such artifacts, the standard does not specify the maximum limit, but it does specify the lower limits.

Here's the reference:

C99 Standard 5.2.4.1 Translation limits:

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

This specifies the lower limit that every implementation must support. Note that in a footenote the standard further says:

18) Implementations should avoid imposing fixed translation limits whenever possible.

链接地址: http://www.djcxy.com/p/91708.html

上一篇: C ++:使用std :: vector :: reserve减少保留空间

下一篇: 我们可以有多少级别的指针?