Advanced C Course – Class 2

Variables and Pointers

In this class we will see perhaps the most advanced functionality of the C language, pointers.

 

In C we can define variables of a particular type that store values ​​that we can access in our program

e.g.
int number = 2;

 

In our program we can access the variable “number” through its name.

Variables is a representation of a memory space that has a physical address.

 

e.g
When we define the variable number, the compiler assigns it at memory address 12000.

 

In our program, instead of accessing the variable by memory address, we access it through its name and it is the compiler itself that is responsible for mapping the variable’s name with its physical memory address.

 

A pointer is a special type of variable that allows us to store the physical address of another variable, so that we can access it through an indirect connection.

e.g
int number = 2;
int * pnumero;

pnumero = & number;
* pnumero = 3;

In this example, pnumero is a pointer that will point to a variable of type integer.
With the assignment pnumero = & number, we are indicating that the pointer points to the variable number.

By assigning a value with * pnumber = 3, we are indirectly modifying the number variable pointed to by the pointer.

Pointers are used to
. allocate dynamic memory at runtime.
. passing parameters to functions by reference
. access to text strings
. indirectly access a variable and be able to change it at runtime.

Leave a Reply

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