Pointers – C/C++ Language

shape
shape
shape
shape
shape
shape
shape
shape

Pointer is a C language feature that consists of:

  • Pointing to or accessing memory addresses.
  • Access variables that are not accessible in a function.
  • Return one or more values in a function.
  • Among others…

How to declare a pointer:

Tipo *Variável;

Example:

#include 

void main()
{
int *p, q;
q = 1;
p = &q;
printf("P: %d", &q);
}

In the example above, a pointer ‘p’ and a variable ‘q’ are declared, ‘q’ receives 1 and ‘p’ receives the memory address of the variable ‘q’, it is worth remembering that the & (‘e’ commercial) shows the memory address, as ‘p’ is a pointer then it will point to the value that is stored in that memory address. Imagine numbered drawers in a closet, we can imagine these as memory addresses and what the pointer does is point to the number of the drawer, showing its contents:

Using pointers in functions:

#include 

void func(int *p);

void main()
{
int x;
x = 1;
printf("Valor de X antes da funcao: %d", x);

//Chamando função.
func(&x);

//Exibe valor de x depois de executar a função.
printf("\nValor de X depois da funcao: %d", x);
}

void func(int *p)
{
//Ponteiro *P apontando para o endereço de memória da variável X na função main() ou principal.
printf("\nPonteiro P: %d", *p);

//Altera valor da variável X.
*p = 2;
}

The above program will have the following output:

Value of X before the function: 1
Pointer P: 1
Value of X after the function: 2

The variable ‘x’ is declared with a value of 1, the memory address of the variable ‘x’ is passed to the pointer ‘p’ via the parameters of the function ‘func’, then ‘p’ points to the address of ‘x’ and assigns the value 2.

Leave a Reply

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

Latest news

Latest news directly from our blog.