Pointers in C Programming [Complete Guide]

pointers in c programming

Pointer is one of the most important concepts in C Programming and it is very difficult to master in Pointers.

Pointers are just like variables. We can declare a pointer of any data type (int, char, float, double) just like we declare variables.

If we declare a variable of int, then that variable can contain only integer value or if we declare a variable of char then that variable can contain the only character in it.

The same concept is here with just one difference.

What are Pointers?

Pointers are variables whose values are memory addresses. Pointers only point to variables.

We can declare a pointer of any data type, if we declare a pointer of integer then that pointer can contain the address of an integer variable or if we declare a pointer of character then that variable can contain the address of any character variable.

In short, variables can contain the values directly and pointers can contain the addresses of that variables.

Declaration of a Pointer:

If we declare a variable and put an asterisk before variable name then that variable becomes a pointer just like that
int *numberPtr;
Here, numberPtr is a pointer of int and can contain the address of an integer variable in it.

How to assign the address to Pointer?

Let, say we have an integer variable xyz and have value 7 in it.
int xyz = 7;
We can assign the address of this integer variable to the pointer we have declared first by using address operator (&). Just like that
numberPtr = &xyz;
Now the pointer numberPtr have the address of variable xyz in it or pointing to variable xyz.

You can understand by this
pointer pointing to the variable xyz
The pointer numberPtr is now pointing to the variable xyz.

Dereferencing:

If we print the value of pointer numberPtr just as we print values of variables then this would not print the exact result you expect because the numberPtr does not have the value you want to print. It has the address of the variable xyz.

For example, if you print like
printf("Value of numberPtr: %d ",numberPtr);
then this would not print the value 7 because numberPtr has the address of xyz.

In my computer, it is printing 6356744.

If you want to print the exact value of the variable to which the pointer is pointing then you have to dereference it by using the dereferencing operator (*) in printing. Just like that
printf("Value of numberPtr: %d ",*numberPtr);

This will print the exact value of variable xyz which is 7.

If the pointer is not initialized correctly with some address then the dereferencing will lead to error.

Comments

Popular posts from this blog

c/c++ Programming questions || Practice Problems for Beginners || C Programs List

Change your Application background in Scene Builder || JavaFX FXML Tutorial

Implementation of Graph in C || Directed and Undirected Graph