Here, we will talk about the basic idea of Pointer in C programming.
What is a pointer?
Like any variable, Pointer is a variable like a reference that holds a memory to another variable, arrays.
And many tasks are easily done by pointers. Like,
• Always works on the original variable.
• We can easily create any data structure.
• Searching and sorting huge data very easily.
• Returning more than one value in the functions.
Now let’s see the basic and simple form of pointers. Suppose there is an integer variable age, and we want to print the memory location of the variable and also the age.
%p is used to display the memory address, and the operator & is used to display the memory location. The output will be:
the memory location will give the hexadecimal.
We can also store this ‘0061FF1C’ address in a separate variable, like a reference, which is the pointer. Now, to make a pointer, we have to make sure the pointer variable is the same as the variable we are pointing to. If the variable is an integer, then the pointer type will be an integer; if the variable is a character, then the pointer type will be a character.
Here, pAge has its own address, but the value stored within it is another address, and we can store it using the ‘*’ or the indirection operator.
Here, we print the address stored in pAge using %p.
POINTER DECLARATION AND POINTER INITIALIZATION
If we break it down, then int *pAge;
is declaring the pointer, and int *pAge = &age;
is initializing the pointer, i.e we are storing the memory location of variable age in the pointer pAge.
DEREFERENCING
Now, suppose we want to access the value at the stored address. We can simply do it using the ‘*’ or the indirection operator. Simply put, we want to find the value at the address, which is called dereferencing.
POINTERS ONLY USING THE OPERATORS
There is another way by which we can find the value stored in a memory address without assigning a pointer using '%d', '%c', or ‘%f’ based on the type of variable. For example.
Size of pointers
Now, in C, the size of the pointer varies according to its type.
for example, the size of the int, char, double or float type is different
OUTPUT
So, from here, we can see that the size of each variable is 8 bytes, but when we assign it to a pointer variable, the size of an integer and a float is 4 bytes, the size of a character is 1 byte, and the size of a double type is 8 bytes.
EXAMPLES
Check here for few basic examples of Pointers
MORE
Since the pointer in C stores the memory address, its size is independent. It depends on the system's architecture.
Pointers are used in many other cases. For example.
To pass the values by reference
To do system-level programming where memory addresses are useful.
To access the values of an array easily.
To return Multiple values from a function.
And many more other uses, which we will talk about later.
Top comments (0)