DEV Community

julio
julio

Posted on

Pointer in C

0. What are pointers?

Pointer is a data type that stores a memory address of a variable type. Pointers are widely used in C to handle data structures, dynamically allocate memory, and optimize performance in certain situations.

Every variable is associated with three things: datatype, name, value and address, that are stored in memory. We can easily access the address, using & before variable. Below is how we can see a address of a variable in C:

int variable = 2;
printf("The address of variable = %p.\n", &variable);
Enter fullscreen mode Exit fullscreen mode

The function of pointer how i said above is store the address of a determinate variable, in code it works like that:

int *pointer = &variable;
Enter fullscreen mode Exit fullscreen mode

or

int *pointer;
pointer = &variable;
Enter fullscreen mode Exit fullscreen mode

When the pointer points nowhere, we give it the value null.

int *pointer2 = NULL;
Enter fullscreen mode Exit fullscreen mode

To see if the pointer is really storing the address of the variable we do another printf to check, and now we just have to see if the addresses are the same.

printf("The address that the pointer stores: = %p.\n", pointer);
Enter fullscreen mode Exit fullscreen mode

Now we can access the value of the "variable" through the pointer thereby using *: (*pointer)

printf("Value of variable: %d || Value of variable through pointer: %d\n", variable, *pointer);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)