Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uses for multiple levels of pointer dereferences?

Tags:

c++

pointers

When does using pointers in any language require someone to use more than one, let's say a triple pointer. When does it make sense to use a triple pointer instead of just using a regular pointer?

For example:

char  * * *ptr; 

instead of

char *ptr; 
like image 882
Jake Avatar asked Apr 17 '09 01:04

Jake


People also ask

Which are various uses of pointers?

Uses of pointers:To return multiple values. Dynamic memory allocation. To implement data structures. To do system-level programming where memory addresses are useful.

What is a pointer jargon pointer & how it is useful in memory optimization?

Pointers are the variables that are used to store the location of value present in the memory. A pointer to a location stores its memory address. The process of obtaining the value stored at a location being referenced by a pointer is known as dereferencing.

What is the maximum level that we can create for pointer to pointer?

This is called levels of pointers. According to ANSI C, each compiler must have at least 12 levels of pointers. This means we can use 12 * symbols with a variable name. Level of pointers or say chain can go up to N level depending upon the memory size.

Can you dereference twice?

You dereference it once you get the pointer it was pointing to, dereference it twice you get the object pointed to by the pointer ptr_ptr is pointing to. I really expected this to be a duplicate, but surprisingly it's not. Definitely worth an answer.


1 Answers

each star should be read as "which pointed to by a pointer" so

char *foo; 

is "char which pointed to by a pointer foo". However

char *** foo; 

is "char which pointed to by a pointer which is pointed to a pointer which is pointed to a pointer foo". Thus foo is a pointer. At that address is a second pointer. At the address pointed to by that is a third pointer. Dereferencing the third pointer results in a char. If that's all there is to it, its hard to make much of a case for that.

Its still possible to get some useful work done, though. Imagine we're writing a substitute for bash, or some other process control program. We want to manage our processes' invocations in an object oriented way...

struct invocation {     char* command; // command to invoke the subprocess     char* path; // path to executable     char** env; // environment variables passed to the subprocess     ... } 

But we want to do something fancy. We want to have a way to browse all of the different sets of environment variables as seen by each subprocess. to do that, we gather each set of env members from the invocation instances into an array env_list and pass it to the function that deals with that:

void browse_env(size_t envc, char*** env_list); 
like image 140
SingleNegationElimination Avatar answered Sep 28 '22 05:09

SingleNegationElimination