Features and Use of Pointers in C/C++
What is a pointer?
A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an int) of the same type. The pointer is given the address of the variable you are working with.
However, each variable has its address in addition to its value (or, put, where it is in the Memory). The address can be obtained by prefixing the variable name with an ampersand (&).
The Use of Pointers in C/C++
A variable's address will appear utterly random if you print it on the screen (moreover, it can be different from run to run). Computer memory consists of bytes. Each byte has a fixed number of bits, 8 for most types of computers. A number identifies each byte called its address. Variables in a C or C++ program correspond to a series of bytes with consecutive addresses.
The lowest of these consecutive addresses is the address of the variable. A pointer is a variable that holds an address. Pointers to void hold addresses of bytes, and pointers to a type of hold addresses of variables of that type. Address 0 is not considered to be a valid address. But it's common in C and C++ for pointers to be set to address 0, which means they are not pointing to anything.
Technically, a pointer is the same thing as a size_t(unsigned long long) variable. We use them to store memory addresses. But there is more to it than just that.
You see, to the programmer and the compiler, a pointer represents two things:
1. The memory address that it points to.
2. The "type" of the data it points to.
How does the "type of the data" help?
- It helps with readability (If I see an (int*).
- It helps with pointer arithmetic.
E.g., in a 32bit Environment, an int pointer would jump 4 bytes ahead when you do a pointer++. Because sizeof(int)=4, but a char pointer would only jump 1 byte because the size of(char) is 1.
There are two types of pointers:
1)Pointers to primitive types.
2)Pointers to user-defined types.
But the data that a pointer holds is always the same kind-" Memory address."
Syntax:
datatype *var_name;
Example:
int *ptr;
Where int is the datatype and ptr is the pointer.
Declaration
Int *ptr=&var;
A pointer is initialized using a variable address after being declared, just like standard variables. The outcomes are unexpected and fatal if pointers in C programming are not uninitialized and utilized in the program.
We put the ampersand (&) operator before the name of a variable whose address we need to obtain to obtain its address. The syntax for initializing pointers is as follows.
Program
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a=10;
int *ptr=&a;
cout<<*ptr<<endl;
return 0;
}
Output:
10
Another way to declare the pointer:
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a=10;
int *ptr;
ptr=&a;
cout<<*ptr<<endl;
return 0;
}
Output:
10
If the value is changed in the pointer, then changes will also be reflected in the original variable.
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a=10;
int *ptr;
ptr=&a;
*ptr=20;
cout<<"Pointer: "<<*ptr<<endl;
cout<<"Variable: "<<a<<endl;
return 0;
}
Output:
Pointer: 20
Variable: 20
If a variable is changed, pointer will also be changed.
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a=10;
int *ptr;
ptr=&a;
a=20;
cout<<"Pointer: "<<*ptr<<endl;
cout<<"Variable: "<<a<<endl;
return 0;
}
Output:
Pointer: 20
Variable: 20
Features of pointers
- Pointers conserve Memory.
- Because data are modified with addresses or direct access to memory locations, pointers have faster execution times.
- The pointers provide efficient access to Memory. The Memory is both assigned and released by the pointer. Thus, it may be claimed that the Memory of pointers is allocated dynamically.
- Data structures employ pointers. They can represent both two-dimensional and multi-dimensional arrays.
- Pointers allow access to any array without considering the subscript range.
- For handling files, pointers are utilized.
- To allocate Memory dynamically, pointers are utilized.
Pointer Types in C
The many types of pointers in C are as follows:
- Null Pointer: We can produce a null pointer by assigning a null value at the pointer declaration. When the pointer has no given address, this approach is helpful. The value 0 is always present in a null pointer.
- Void Pointer: A void pointer is also known as a generic pointer in C programming. There is a variety of data types for it. The keyword void creates a pointer to a void. Any variable's address may be stored in it.
- Wild pointer: If a pointer is not being initialized to anything, it is referred to as a wild pointer. These C pointer types are inefficient because they might point to an unidentified memory location, which could interfere with our program and cause it to crash. When using wild pointers, one should always exercise caution.
Advantages of pointers
- For gaining access to memory regions, pointers are helpful.
- An array structure's elements can be accessed effectively via pointers.
- Both deallocation and dynamic memory allocation require pointers.
- Complex data structures, like linked lists, graphs, trees, etc., are created using pointers.
Drawback of pointers
Pointers are very powerful, but with great power comes great danger. You could accidentally overwrite a system file just because your pointer contained a garbage value. Bugs are common in software; if even one of those bugs contains naked pointers, your computer is at risk.
So, to avoid that danger, HLLs hide pointers behind the implemented data structures and discourage programmers from using them. They encapsulate and obscure pointers so much that you could be programming for thirty years, and you wouldn't realize that you were using pointers.
For all practical purposes, the APIs will suffice. But if you are trying to super-optimize your program, you should investigate the low-level languages and pointers. If you use the pointer such that efficiency would suffer due to extra overhead before reaching the target, you are using pointers incorrectly.
Uses of pointers
- Pointers can save space
Space is very precious & saving space leads to gaining time and, thus, better performance. Suppose you're working with very large data types or you have yourself have created an enormous object. Now, if you want to pass this object to a function, then the compiler will generate a copy of this object in the Memory, then this copy will be passed to the function & then the processing on the value will begin. In this way, you need to use the Memory efficiently because you must create a copy of such a large object without any good reasons. But suppose you pass the address of this variable to the target function. In that case, the processing will be done directly on the original object & hence no time or Memory will be wasted on the duplication of the original object. Thus speed & space efficiency is gained. - They can increase speed during iterative traversal
For example, if you wish to traverse the array, then you'll write a for loop to iterate the index value, but in actuality, you are incrementing the memory address. So, if you're performing conscious back-end coding, then instead of first incrementing the index & then updating the memory address, you can directly access the following memory location & hence performance improvement. - Changes made are observed everywhere
Suppose you have a program with independent threads. Now instead of creating a copy of the same data for each one, you provide them with the address of the original value & thus, if any change is made to the value, then every thread will get the latest updates. - Reading variables not in the same scope
Using pointers, you can access variables which were not declared in the same scope. - Another reason for using pointers is that they enable dynamic memory allocation. For the allocation of dynamic memory, pointers are required. When working with an unknown amount of data, dynamic memory allocation comes in handy since it enables you to build variables, arrays, and more complicated data structures in memory while the program is executing.
- Pointers can also be used in storing elements in the array and accessing those elements from the array. Because the array variable also has an address that a pointer can point to, and the array can be navigated using a pointer.
Example:
#include <stdio.h>
int main() {
int a[5];
printf("Enter elements: ");
for (int i = 0; i < 5; ++i)
scanf("%d", a + i);
printf("You entered: \n");
for (int i = 0; i < 5; ++i)
printf("%d\n", *(a + i));
return 0;
}
Output:
Enter elements: 1 2 3 4 5
You entered:
1
2
3
4
5
Summary
Pointers are used for memory purposes; when using normal data types, you're reserving a memory location for them, whether you use them once or several times. So, with an extensive program would significantly affect the Memory, making the program slower or demanding more Memory from the machine.
Pointers are very useful, and there is a must when going to next-level programming, unlike other languages like java which doesn't contain pointers. Therefore, pointers are a complex and yet most helpful thing in C and C++ programming languages.