459

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;
Parag
  • 7,156
  • 9
  • 21
  • 28
  • 599
    If that ever becomes a real issue for you, you are doing something very wrong. – ThiefMaster Apr 10 '12 at 10:38
  • 292
    You can keep adding levels of pointers until your brain explodes or the compiler melts - whichever happens soonest. – JeremyP Apr 10 '12 at 10:52
  • 51
    Since a pointer to a pointer is again, well, just a pointer, there shouldn't be any theoretical limit. Maybe the compiler won't be able to handle it beyond some ridiculously high limit, but well... – Christian Rau Apr 10 '12 at 10:59
  • 76
    with the newest c++ you should use something like `std::shared_ptr...>>>` – josefx Apr 10 '12 at 14:09
  • 6
    Maybe a "decorated comment" got out of control and fired this question :) – jalopaba Apr 10 '12 at 15:55
  • 3
    Why not just write a simple program to test this on your compiler? Whatever answered by others is likely to not exactly match your environment. – Gowtham Apr 10 '12 at 16:47
  • 4
    @Thecrocodilehunter: Why? What is so destructive (or *unconstructive* ) about it? – Nawaz Apr 10 '12 at 17:52
  • 4
    @Gowtham worst possible advice, it may compile and fail in the next version or it may fail now to a bug in the compiler. check the compiler documentation, check the standard and as last resort check the current implementation. – josefx Apr 10 '12 at 19:43
  • 2
    it can make sense for code generators... – tuxSlayer Apr 10 '12 at 20:33
  • 47
    @josefx - this shows a problem in the C++ standard - there's no way to raise smart pointers to powers. We must immediately demand an extension to support e.g. `(pow (std::shared_ptr, -0.3)) x;` for -0.3 levels of indirection. – Steve314 Apr 11 '12 at 00:05
  • 2
    @Thecrocodilehunter: Mmmm, nah. This is on topic. And if any of you reddit people want to go through my questions/answers and massively upvote them, please feel free! –  Apr 11 '12 at 13:07
  • 2
    @PeterWood the link you provided is gold, just pure gold. – Chad Harrison Apr 11 '12 at 15:18
  • @PeterWood I have had the "joy" of maintaining a three-star programmer's codebase. He also had a tendency to handle all error conditions with `exit(0)` (and nothing else, not even a printf). – fluffy Apr 11 '12 at 17:21
  • 4
    Technically there is probably no limit (although that is compiler specific). The real limit is your (and your coworkers') mental capacity to keep track of what your variable actually represents. Making and keeping the code readable is usually more important than low level optimization. From this point of view, in production code already triple indirection (e.g. `int***`) is discouraged in most cases. – Péter Török Apr 10 '12 at 10:40
  • It depends on your system's memory. If it exceeds that, the system will hang. Otherwise, it's infinite. You can try with `while(1)`. – Trikaldarshiii Apr 11 '12 at 11:33
  • Sure your answer belongs here? – Sebastian Mach Apr 13 '12 at 10:38
  • @phresnel : yupe aren't you sure – Trikaldarshiii Apr 14 '12 at 05:18
  • seems like the correct way to force spaghetti code in cpp :) – thepoosh May 01 '12 at 06:37
  • 1
    well logically it doesnt make any sense to create pointers to this n level. Compiler has no problems, but your program has if it uses so – Sandeep Nair May 03 '12 at 04:41
  • @PeterWood never heard of the word, but recognize so many programmers I've met through the years. Thanks for sharing that brilliant link. – Niels Keurentjes Apr 16 '13 at 22:45
  • @PeterWood I was teased for writing 3-star code once upon a time. Though it was in fact an array of addresses of strings... which is (in my mind) very different from pointer-to-pointer-to-pointer-to-char, as I was accused of. [sigh] I'd still defend that code. – Chris Pine May 12 '14 at 22:43
  • I know lots of 3-star programmers. They are quantum chemists that program 4D arrays in the naive but common fashion. – Jeff Hammond Apr 17 '15 at 05:23
  • 2
    @Steve314: You mean, like this? http://coliru.stacked-crooked.com/a/92a6666764acbaff :D – Lightness Races in Orbit Feb 13 '17 at 18:41
  • Note that there is one pretty common pointer which is usually written with three levels: char*** argv (or often written as char** argv[]). For example this is exactly the way you call MPI_Init (and other functions that may change your argv when passing it). – overseas Mar 03 '17 at 17:11
  • I once had to use a `void****` in a real life program. – Seva Alekseyev May 12 '19 at 16:53
  • @SevaAlekseyev Any program that requires that many levels of pointers is [1] probably very inefficient and [2] most likely has a lot of bugs in it. Just stick with one or two layers of pointers. – S.S. Anne Jun 30 '19 at 03:23
  • Tell that to Microsoft :) The object in question was the pointer to a smart pointer around a COM interface pointer, which effectively points at a pointer to an array of function pointers. With me yet? :) – Seva Alekseyev Jun 30 '19 at 14:17
  • It depends on how much memory you have to store the pointers (which are just variables holding addresses to other variables). Before declaring and initializing a pointer, it doesn't exist in memory. – Andreas K. Apr 24 '20 at 08:01

14 Answers14

407

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.

Sklivvz
  • 28,698
  • 24
  • 111
  • 164
P.P
  • 106,931
  • 18
  • 154
  • 210
  • 121
    The C++ standard "recommends" that an implementation support at least 256. (Readability recommends that you not exceed 2 or 3, and even then: more than one should be exceptional.) – James Kanze Apr 10 '12 at 10:52
  • 22
    This limit is about how many in a single declaration; it does not impose an upper bound on how much indirection you can achieve via multiple `typedef`s. – Kaz Apr 10 '12 at 11:37
  • 11
    @Kaz - yes, that is true. But since the spec is (no pun intended) specifying a mandatory lower limit, it is the effective upper bound all spec-compliant compilers are **required** to support. It could be lower than the vendor-specific upper bound, of course. Rephrased differently (to align it with the OP's question), it is the **maximum** *allowed by the spec* (anything else would be vendor-specific.) A bit off the tangent, programmers *should* (at least in the general case) treat that as their upper limit (unless they have a valid reason to rely on a vendor-specific upper bound)... me thinks. – luis.espinal Apr 10 '12 at 16:00
  • 5
    On another note, I would start to cut myself if I had to work with code that had long-ass dereferencing chains (specially when **liberally peppered all over the place**.) – luis.espinal Apr 10 '12 at 16:03
  • 2
    ok, but why exactly 12? Why not 5 or 40. Is there some explanation for this? – beryllium Apr 13 '12 at 08:00
  • 11
    @beryllium: Usually these numbers come from taking a survey of pre-standardization software. In this case presumably they looked at common C programs and existent C compilers, and found at least one compiler that would have trouble with more than 12 and/or no programs that broke if you restricted it to 12. –  Apr 15 '12 at 14:48
  • I don't understand why a answer get more upvotes just because the writer has more reputation. This way answers which are actually good but by low reputation are hided.This answer was not as much constructive , but its upvotes are massive. Above Sachin Mhetra Answer was good but has so low upvotes. – Suraj Jain Aug 24 '16 at 13:02
  • @SurajJain When I posted my answer my rep was about 1500. All the existing answers were all wrong at that time. Hence, it got many upvotes. Later on, others edited their answers and/or improved *after* I posted my answer. You can see this from the edit history and time stamps of the answers. For example, see Alok Save's initial answer from the [edit history](http://stackoverflow.com/revisions/10087135/1), which was competely wrong. – P.P Aug 26 '16 at 09:34
  • @P.P. Still , sachin mehra answer was constructive and i saw its edit history , no massive change, you jut posted some standard not explaining in your words , and it has above 300 upvotes .Maybe because OP did not asked why and just ask what is the upper limit and best way to tell is show the standard , but it would be nicer if you would explain reasoning also. Like Theoretically And Practically , down mihai user checked it, and showed what is limit and it is implementation specific , all these things in one answer makes it deserving for all those upvote ,not just referring to the standard. – Suraj Jain Aug 26 '16 at 18:08
  • @SurajJain If it's not upto what your standard, you can post a better answer. If you are concerned about "deservedness" of upvotes you can flag it to a moderator and explain the right number of upvotes this should have and see if they can help you. – P.P Aug 27 '16 at 16:01
159

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

Kaz
  • 48,579
  • 8
  • 85
  • 132
  • 51
    That's a completely different issue, though - a struct containing a pointer to another struct is very different than a pointer-pointer. An int***** is a distinct type from an int****. – fluffy Apr 11 '12 at 17:22
  • 14
    It is not "very" different. The difference is fluffy. It is closer to syntax than semantics. A pointer to a pointer object, or a pointer to a structure object which contains a pointer? It's the same kind of thing. Getting to the tenth element of a list is ten levels of addressing indirection. (Of course, the ability to express an infinite structure depends on the struct type being able to point to itself via the incomplete struct type so that `list->next` and `list->next->next` are the same type; otherwise we would have to construct an infinite type.) – Kaz Apr 11 '12 at 18:28
  • 38
    I didn't consciously notice that your name is fluffy when I used the word "fluffy". Subsconscious influence? But I am sure I have used the word in this way before. – Kaz Apr 11 '12 at 18:29
  • 1
    Hmmm! I'm not sure this is really an infinite pointer indirection. Semantically speaking you're dealing with only one type (`struct list *`) and only one pointer is dereferenced _at a time_, each padded by an "almost no op". (As has already been practically pointed out, but hey.) – nitro2k01 Apr 11 '12 at 22:01
  • 1
    In C, one pointer is dereferenced at a time no matter what. You cannot dereference the next pointer until you load the previous one. `*******x` is one at a time, exactly like `x->next->next->next->next`. – Kaz Apr 11 '12 at 22:04
  • 4
    Also remember that in machine language, you could just iterate on something like `LOAD R1, [R1]` as long as R1 is a valid pointer at every step. There are no types involved other than "word which holds an address". Whether or not there are declared types doesn't determine the indirection and how many levels it has. – Kaz Apr 12 '12 at 03:56
  • +1. But in the strict sense - for having infinite number of indirections - we must have infinite address space, which isn't the case. – Agnius Vasiliauskas Apr 19 '12 at 10:44
  • 4
    Not if the structure is circular. If `R1` holds the address of a location which points to itself then `LOAD R1, [R1]` can be executed in an infinite loop. – Kaz Apr 19 '12 at 19:11
  • 2
    This answer is not answering the question asked, which is about declarations. – Bryan Apr 30 '14 at 09:28
  • @Bryan it certainly is about a declarations. The struct declaration is self-referential ("I contain a pointer to myself"), something which C painstakingly allows via the incomplete struct type mechanism. This creates an infinite level of pointer indirection. – Kaz Apr 30 '14 at 17:51
  • @Kaz the point is that traversal of a long chain of `->next` elements is controlled by the programmer; to handle `*****....*****int` the compiler has to internally represent the depth of the pointers (so it can detect incorrect dereferencing). Some ways of storing this representation may only be limited by memory (used by the compiler) but some methods may have hard limits. – TripeHound Jul 20 '15 at 13:03
  • @TripeHound `P->memb` and `*P` are both syntax. How deeply that syntax is nested is controlled by the programmer. The compiler has to represent `P->memb->memb->memb->memb...` and it has to represent `***..P`. – Kaz Jul 21 '15 at 14:23
  • There is a difference, mainly during compilation. For `P->next` that happens to point to another `P`, the compiler only needs to know that it is a pointer to the parent structure. At _compile time_ it doesn't care how long a string of linked elements you create at runtime. For `*****int`, the compiler _at compile time_ has to represent the type _for every level_ ... that is `*****int` is a pointer to a `****int` which points to `***int` ... to a `*int` which finally points to an `int`. For _some_ compilers, under _some_ conditions, it may run out of space to do so. – TripeHound Jul 21 '15 at 14:31
  • @TripeHound You can get avoid constructing a deep static type by using something like `DEREFI(DEREFV(DEREFV...(DEREFV(P)) ...))` where `P` is a `void *` pointer, `DEREFV` is `#define DEREFV(P) (*((void **) (P)))` and `DEREFI` is similar, but with a cast to `int *`. I.e. an arbitrarily long chain of `void *` pointers that point to `void *`, and finally an `int`. – Kaz Jul 21 '15 at 16:25
83

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Alok Save
  • 190,255
  • 43
  • 403
  • 518
  • 16
    indirections don't overflow any stacks! – Basile Starynkevitch Apr 10 '12 at 10:37
  • 1
    Corrected, I had this errie feeling of reading & answering the q as limit of parameters being passed to the function. I don't know why?! – Alok Save Apr 10 '12 at 10:39
  • 2
    @basile - I'd expect stack-depth to be an issue in the parser. Many formal parsing algorithms have a stack as a key component. Most C++ compilers probably use a variant of recursive descent, but even that relies on the processor stack (or, pedantically, on the language acting as if there was a processor stack). More nesting of grammar rules means a deeper stack. – Steve314 Apr 11 '12 at 00:14
  • 8
    _indirections don't overflow any stacks!_--> No! parser stack can overflow. _How does the stack relate to pointer indirection?_ Parser stack! – Pavan Manjunath Apr 11 '12 at 07:15
  • If `*` is overloaded for a number of classes in a row, and each overload returns an object of other type in the row, then there can be stackoverflow for such chained function calls. – Nawaz May 27 '12 at 05:10
  • @PéterTörök may be stack matter while compiler parse an expression consist of many `*`s – Grijesh Chauhan Jul 03 '13 at 08:03
  • From a practical perspective, the translation limits are at best recommendations, since the Standard says nothing about what combinations of limits must be supported. Many real-world implementations would die if code tried to include the maximum allowable number of parameters and automatic objects in a function, and they all took 32767 bytes each. On the other hand, nothing in the Standard would forbid a conforming-but-useless implementation from saying that no function can both contain more than one automatic object and have any automatic object which is larger than one byte in size. – supercat Aug 15 '18 at 19:16
  • The authors of the Standard acknowledged the possibility of conforming-but-useless implementations, but expected that (1) people making a bona fide effort to produce a usable implementation won't do stupid things merely because the Standard would allow them to, and (2) it wasn't worth worrying about what kinds of compilers might be produced by people who weren't making such an effort. – supercat Aug 15 '18 at 19:20
78

As people have said, no limit "in theory". However, out of interest I ran this with g++ 4.1.2, and it worked with size up to 20,000. Compile was pretty slow though, so I didn't try higher. So I'd guess g++ doesn't impose any limit either. (Try setting size = 10 and looking in ptr.cpp if it's not immediately obvious.)

g++ create.cpp -o create ; ./create > ptr.cpp ; g++ ptr.cpp -o ptr ; ./ptr

create.cpp

#include <iostream>

int main()
{
    const int size = 200;
    std::cout << "#include <iostream>\n\n";
    std::cout << "int main()\n{\n";
    std::cout << "    int i0 = " << size << ";";
    for (int i = 1; i < size; ++i)
    {
        std::cout << "    int ";
        for (int j = 0; j < i; ++j) std::cout << "*";
        std::cout << " i" << i << " = &i" << i-1 << ";\n";
    }
    std::cout << "    std::cout << ";
    for (int i = 1; i < size; ++i) std::cout << "*";
    std::cout << "i" << size-1 << " << \"\\n\";\n";
    std::cout << "    return 0;\n}\n";
    return 0;
}
BoBTFish
  • 17,936
  • 3
  • 49
  • 73
  • 73
    I couldn't get more than 98242 when I tried it. (I did the script in Python, doubling the number of `*` until I got one that failed, and the preceding one that passed; I then did a binary search over that interval for the first one that failed. The whole test took less than a second to run.) – James Kanze Apr 10 '12 at 11:31
63

Sounds fun to check.

  • Visual Studio 2010 (on Windows 7), you can have 1011 levels before getting this error:

    fatal error C1026: parser stack overflow, program too complex

  • gcc (Ubuntu), 100k+ * without a crash ! I guess the hardware is the limit here.

(tested with just a variable declaration)

mihai
  • 32,161
  • 8
  • 53
  • 79
  • 5
    Indeed, the productions for unary operators are right-recursive, which means that a shift-reduce parser will shift all of the `*` nodes onto the stack before being able to make a reduction. – Kaz Apr 10 '12 at 19:15
29

There is no limit, check example here.

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."

int i = 0;

int *ip01 = & i;

int **ip02 = & ip01;

int ***ip03 = & ip02;

int ****ip04 = & ip03;

int *****ip05 = & ip04;

int ******ip06 = & ip05;

int *******ip07 = & ip06;

int ********ip08 = & ip07;

int *********ip09 = & ip08;

int **********ip10 = & ip09;

int ***********ip11 = & ip10;

int ************ip12 = & ip11;

************ip12 = 1; /* i = 1 */

If you mean "How many levels of pointer can you use before the program gets hard to read," that's a matter of taste, but there is a limit. Having two levels of indirection (a pointer to a pointer to something) is common. Any more than that gets a bit harder to think about easily; don't do it unless the alternative would be worse.

If you mean "How many levels of pointer indirection can you have at runtime," there's no limit. This point is particularly important for circular lists, in which each node points to the next. Your program can follow the pointers forever.

Nandkumar Tekale
  • 14,991
  • 7
  • 52
  • 85
  • 7
    There's almost certainly a limit, since the compiler has to keep track of the information in a finite amount of memory. (`g++` aborts with an internal error at 98242 on my machine. I expect that the actual limit will depend on the machine and the load. I also don't expect this to be a problem in real code.) – James Kanze Apr 10 '12 at 11:12
  • 2
    Yeah @MatthieuM. : I just considered theoretically :) Thanks James for completing answer – Nandkumar Tekale Apr 10 '12 at 11:20
  • 3
    Well, linked lists aren't really a pointer to a pointer, they're a pointer to a struct that contains a pointer (either that or you end up doing a lot of unnecessary casting) – Random832 Apr 10 '12 at 13:58
  • @Random832 : Yeah! but don't you think it is well structured? – Nandkumar Tekale Apr 10 '12 at 14:11
  • 1
    @Random832: Nand said 'If you mean "How many levels of pointer indirection can you have at runtime,"' so he was explicitly removing the restriction of just talking about pointers to pointers (*n). – LarsH Apr 10 '12 at 15:46
  • 1
    I don't get your point: '_There is no limit, check example here._' The example is no proof that there is no limit. It only proves that a 12 star indirection is possible. Neither proves anything the `circ_list` example regarding the OP's question: The fact that you can traverse a pointers list doesn't imply that the compiler can compile a n-stars indirection. – Alberto Apr 11 '12 at 14:18
  • I mean, There is no limit and for more info check that example. Think on circ_list example. – Nandkumar Tekale Apr 11 '12 at 14:40
25

It's actually even funnier with pointer to functions.

#include <cstdio>

typedef void (*FuncType)();

static void Print() { std::printf("%s", "Hello, World!\n"); }

int main() {
  FuncType const ft = &Print;
  ft();
  (*ft)();
  (**ft)();
  /* ... */
}

As illustrated here this gives:

Hello, World!
Hello, World!
Hello, World!

And it does not involve any runtime overhead, so you can probably stack them as much as you want... until your compiler chokes on the file.

Matthieu M.
  • 251,718
  • 39
  • 369
  • 642
22

There is no limit. A pointer is a chunk of memory whose contents are an address.
As you said

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

A pointer to a pointer is also a variable which contains an address of another pointer.

int **q = &p;

Here q is pointer to pointer holding the address of p which is already holding the address of a.

There is nothing particularly special about a pointer to a pointer.
So there is no limit on chain of poniters which are holding the address of another pointer.
ie.

 int **************************************************************************z;

is allowed.

Sachin Mhetre
  • 4,225
  • 10
  • 39
  • 65
18

Every C++ developer should have heard of the (in)famous Three star programmer

And there really seems to be some magic "pointer barrier" that has to be camouflaged

Quote from C2:

Three Star Programmer

A rating system for C-programmers. The more indirect your pointers are (i.e. the more "*" before your variables), the higher your reputation will be. No-star C-programmers are virtually non-existent, as virtually all non-trivial programs require use of pointers. Most are one-star programmers. In the old times (well, I'm young, so these look like old times to me at least), one would occasionally find a piece of code done by a three-star programmer and shiver with awe. Some people even claimed they'd seen three-star code with function pointers involved, on more than one level of indirection. Sounded as real as UFOs to me.

Mare Infinitus
  • 7,602
  • 7
  • 55
  • 106
13

Note that there are two possible questions here: how many levels of pointer indirection we can achieve in a C type, and how many levels of pointer indirection we can stuff into a single declarator.

The C standard allows a maximum to be imposed on the former (and gives a minimum value for that). But that can be circumvented via multiple typedef declarations:

typedef int *type0;
typedef type0 *type1;
typedef type1 *type2; /* etc */

So ultimately, this is an implementation issue connected to the idea of how big/complex can a C program be made before it is rejected, which is very compiler specific.

Kaz
  • 48,579
  • 8
  • 85
  • 132
6

I'd like to point out that producing a type with an arbitrary number of *'s is something that can happen with template metaprogramming. I forget what I was doing exactly, but it was suggested that I could produce new distinct types that have some kind of meta maneuvering between them by using recursive T* types.

Template Metaprogramming is a slow descent into madness, so it is not necessary to make excuses when generating a type with several thousand level of indirection. It's just a handy way to map peano integers, for example, onto template expansion as a functional language.

JDługosz
  • 4,053
  • 2
  • 20
  • 39
4

Rule 17.5 of the 2004 MISRA C standard prohibits more than 2 levels of pointer indirection.

kostmo
  • 5,782
  • 4
  • 37
  • 51
  • 16
    Pretty sure that's a recommendation for programmers, not for compilers. – Cole Johnson Feb 07 '14 at 02:16
  • 3
    I read the document with rule 17.5 about more than 2 levels of pointer indirection. And it doesn't necessarily prohibit more than 2 levels. It does state that the ruling should be followed as more than 2 levels is `"non-compliant"` to their standards. The important word or phrase in their ruling is the use of the word `"should"` from this statement: `Use of more than 2 levels of indirection can seriously impair the ability to understand the behavior of the code, and should therefore be avoided.` These are guidelines set by this organization as opposed to rules set by the language standard. – Francis Cugler Nov 24 '17 at 04:48
0

There isn't such a thing like real limit but limit exists. All pointers are variables that are usually storing in stack not heap. Stack is usually small (it is possible to change its size during some linking). So lets say you have 4MB stack, what is quite normal size. And lets say we have pointer which is 4 bytes size (pointer sizes are not the same depending on architecture, target and compiler settings).

In this case 4 MB / 4 b = 1024 so possible maximum number would be 1048576, but we shouldn't ignore the fact that some other stuff is in stack.

However some compilers may have maximum number of pointer chain, but the limit is stack size. So if you increase stack size during linking with infinity and have machine with infinity memory which runs OS which handles that memory so you will have unlimited pointer chain.

If you use int *ptr = new int; and put your pointer into heap, that is not so usual way limit would be heap size, not stack.

EDIT Just realize that infinity / 2 = infinity. If machine has more memory so the pointer size increases. So if memory is infinity and size of pointer is infinity, so it is bad news... :)

ST3
  • 8,050
  • 2
  • 62
  • 85
  • 4
    A) Pointers can be stored on the heap (`new int*`). B) An `int*` and an `int**********` have the same size, at least on reasonable architectures. –  Jul 30 '13 at 07:23
  • @rightfold A) Yes pointers can be stored in heap. But it would be very different thing like creating container which hold pointers what are pointing to the next previous pointer. B) Of course `int*` and an `int**********` have the same size, I didn't said that they have different. – ST3 Jul 30 '13 at 07:28
  • 2
    Then I don't see how stack size is even remotely relevant. –  Jul 30 '13 at 07:28
  • @rightfold I've been thinking about _usual_ way of data distribution when all data is in heap and on stack it is just pointers to that data. It would be _usual_ way, but I agree that it is possible to put pointers in stack. – ST3 Jul 30 '13 at 07:31
  • "Of course int* and an int********** have the same size" - the standard doesn't guarantee that (although I know of no platform where it isn't true). – Martin Bonner supports Monica Mar 22 '18 at 09:12
-1

It depends on the place where you store pointers. If they are in stack you have quite low limit. If you store it in heap, you limit is much much much higher.

Look at this program:

#include <iostream>

const int CBlockSize = 1048576;

int main() 
{
    int number = 0;
    int** ptr = new int*[CBlockSize];

    ptr[0] = &number;

    for (int i = 1; i < CBlockSize; ++i)
        ptr[i] = reinterpret_cast<int *> (&ptr[i - 1]);

    for (int i = CBlockSize-1; i >= 0; --i)
        std::cout << i << " " << (int)ptr[i] << "->" << *ptr[i] << std::endl;

    return 0;
}

It creates 1M pointers and at the shows what point to what it is easy to notice what the chain goes to the first variable number.

BTW. It uses 92K of RAM so just imagine how deep you can go.

ST3
  • 8,050
  • 2
  • 62
  • 85