C Pointers Made Easy

For newcomers to C, whether you are new to programming in general or just are used to living in HLL land, pointers can get confusing fast. Here is one trick I used to keep my code readable when I was getting my C sea-legs.

Prepend ‘p_’ to pointer variables and ‘pp_’ to pointers to pointers

To make C pointer code more readable, you can add some mnemonics to your variable names like so:

int num_cookies       = 100;

int * p_num_cookies   = &num_cookies;   /* The 'p_' helps us remember later that this is a pointer to num_cookies */

int ** pp_num_cookies = &p_num_cookies;  /* The 'pp_' helps us remember later that this a pointer to a pointer (p_num_cookies) */

=========================================

’*p_’ cancels out

Having the ‘p_’ in our pointer names helps us later when we want to derefence something. We can easily read what is going on without having to backtrack or try to keep it all in our own human working memory. Like so:

*p_num_cookies    => (the * and the p cancel each other out and you know it means: ) => num_cookies

*pp_num_cookies   => (the * and the FIRST p cancel each other out and you know it means:) => p_num_cookies

**pp_num_cookies  => (the ** and the pp_ cancel each other out and you know it means:) => num_cookies

===========================================================

Assignments are less error-prone too

This also comes in super handy when doing assignments because you know you are assigning things at the correct level:

**pp_num_cookies  = 45;         /* you know you are assgining 45 to the value of num_cookies since the **pp_ cancels out */

*pp_num_cookie    = p_num_desserts;   /* you know you are assigning an int pointer to an int pointer because the * and the first p cancel out */ 
Written on February 18, 2017