C pointer introduction

Introduction to C pointers

The pointer is one of the most confusing/challenging parts ofC, in my opinion. Especially if you are not familiar with programming, but if you come from a higher-level programming language such as Python or JavaScript.

In this article, I want to introduce them in the simplest but not vague way.

The pointer is the address of the memory block that contains the variable.

When you declare such an integer:

int age = 37;

We can use&Operator, used to get the address value in the variable memory:

printf("%p", &age); /* 0x7ffeef7dcb9c */

I used%pSpecified formatprintf()Print the address value.

We can assign addresses to variables:

int *address = &age;

useint *addressIn the declaration, we are not declaring integer variables, we are declaringPointer to integer.

We can use pointer operators*Get the value of the variable pointed to by the address:

int age = 37;
int *address = &age;
printf("%u", *address); /* 37 */

This time we use the pointer operator again, but since it is not a declaration this time, it means "the value of the variable pointed to by the pointer".

In this example, we declare aageVariables, we use a pointer to initialize the value:

int age;
int *address = &age;
*address = 37;
printf("%u", *address);

When using C, you will find that many things are built on this simple concept, so make sure to get a little familiar with it by running the above example yourself.

Pointers are a great opportunity because they force us to consider memory addresses and the way data is organized.

ArrayJust an example. When declaring an array:

int prices[3] = { 5, 4, 3 };

ThispricesThe variable is actually a pointer to the first item of the array. You can use this to get the value of the first itemprintf()Function in this case:

printf("%u", *prices); /* 5 */

The cool thing is that we can get the second item by adding 1 to the second item.pricespointer:

printf("%u", *(prices + 1)); /* 4 */

For all other values, and so on.

We can also perform many nice string manipulation operations, because strings are internal arrays.

We have more applications, including passing references to objects or functions to avoid wasting more resources to copy it.

Download mine for freeC manual

More clang tutorials: