Skip to main content

Command Palette

Search for a command to run...

I learnt something new about pointers.

Published
2 min read
I learnt something new about pointers.
X

"I am currently a Software Engineering student at ALX. I'm passionate about technology and enjoy conducting research to find answers on my own. I have a natural inclination to ask 'WHY' more often than 'HOW'.

"While working on projects at ALX, I have acquired a wealth of interesting and diverse knowledge about software engineering and computer science in general. Therefore, I needed a place to store and save all this information, allowing me to refer back to it whenever I forget."

'*' can be used for pointer declaration and also as an indirection operator/valueof operator. its meaning depends on the context used.
Pointers only store addresses not values

Eg: int a = 10;
Pointer declaration and initialization, are still done with '*'
int *p = &a;

OR

int *p; p = &a;

Accessing a pointer
we also access the value at the address stored in p using a '*'

int val = *p;

*p means get the value at p, it asks the question what is the value at p
if address of the variable a is 1000 for an example
*p == *(&a) == *(1000) == 10
*(1000) means get the value at 1000

Double Pointers

since pointers are been delclared with '*', and the left side value says the kind of value it's pointing to, the same rule applies to double pointers.

int *p means p is a pointer to an address that contains an integer value. recall that pointers stores only addresses therefore to declare a double pointer q, we start with *q

*q means q will store an address(ie q is a pointer to something) now what will it point to? it's going to point to a pointer what is the type of the pointer? in our case 'int *'

so we place 'int *' in front of *q
therefore int **q is now a double pointer

so q is a pointer to a pointer
if p is stored at an address 2000
*q == *(&p) == *(2000) which means get the value of 2000 which will evaluate to 1000 because the p holds the address of the value a so to access the value a, we add another '*'
*(*(&p)) == *(&a) == *(1000) == 10
recall that '*' at declaration is not the same with '*' when accessing the values(value of)
at declaration '*' says whether a variable is a pointer or a double pointer
as a value-of operator its says whether to access a pointer or pointer to a pointer

now to prove to you that pointers are so easier, let's do for a pointer to a pointer to a pointer :)

if q is been stored at the address 3000, a pointer to q will be
*r means r will store an address(a pointer to something). now what type of value will it be pointing to
'int **' this is q type
then int ***r is now a pointer to q that points to p that points to a

to access a, we do this
*(*(*(3000))) *(*(2000)) *(1000) 10

More from this blog

PERSONAL BLOG

110 posts

Use the search button to search for a specific topic or keyword *all posts are updated on the go*