Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read C++ pointer construct?

Tags:

c++

pointers

This is a newbie C++ question. What is the difference between the following two constructs?

1. const int* const* const x
2. const int**

How do I read these constructs?

like image 835
codefx Avatar asked Nov 23 '12 23:11

codefx


People also ask

How do I print the value of a pointer?

You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.

How does pointer work in C?

The Pointer in C, is a variable that stores address of another variable. A pointer can also be used to refer to another pointer function. A pointer can be incremented/decremented, i.e., to point to the next/ previous memory location. The purpose of pointer is to save memory space and achieve faster execution time.

What is the output of C program with pointers?

16) What is the output of C program with structures pointers.? Explanation: F2.


3 Answers

How do I read these constructs?

Read them backwards and read the * as "pointer to".

const int* const* const

is a constant pointer to a constant pointer to an integer constant.

const int**

is a pointer to a pointer to an integer constant.

like image 127
Pubby Avatar answered Oct 02 '22 00:10

Pubby


It gets a bit easier if you group things the right way. For example, *const is really one unit meaning "const pointer to" (you can read the const as a subscript here: *const). I'd write it as:

const int *const *const p1; // p1 is a const pointer to const pointer to const int
const int **p2; // p2 is a pointer to pointer to const int

Also remember that declarations read "inside out", starting at the identifier being declared.

like image 38
melpomene Avatar answered Oct 01 '22 22:10

melpomene


There is a tool that's useful/fun to decipher declarations: http://cdecl.ridiculousfish.com/

In your case it reports: const int* const* const x => declare x as const pointer to const pointer to const int const int** x => declare x as pointer to pointer to const int

like image 38
frozenkoi Avatar answered Oct 01 '22 22:10

frozenkoi