c. Pointers

Common mistakes when working with pointers

Suppose, you want pointer pc to point to the address of c. Then,

int c, *pc;

// pc is address but c is not
pc = c;  // Error

// &c is address but *pc is not
*pc = &c;  // Error

// both &c and pc are addresses
pc = &c;  // Not an error

// both c and *pc values 
*pc = c;  // Not an error

Here’s an example of pointer syntax beginners often find confusing.

#include <stdio.h>
int main() {
   int c = 5;
   int *p = &c;

   printf("%d", *p);  // 5
   return 0; 

Why didn’t we get an error when using int *p = &c;?

It’s because

int *p = &c;

is equivalent to

int *p:
p = &c;

In both cases, we are creating a pointer p (not *p) and assigning &c to it.

To avoid this confusion, we can use the statement like this:

int* p = &c;

Leave a Reply

Your email address will not be published. Required fields are marked *