Pointer and Array In C++
Pointer vs Array :
A pointer is a type of variable that keeps as its value the memory address of another variable while an array is defined as the consecutive block of sequence which can store similar type of data.
Basic Definition
Array Definition :
Array is defined as the continuous block of memory in which a similar data type is stored. Array indexing starts with size 0 and ends with size -1. The size of the array is fixed and it is stored in static memory.
Pointer Definition :
Pointers in C++ language are is nothing but sort of like a variable which works like a locator/indicator to an address values (hence the name pointer).It helps in reducing the code and returning multiple values from a function.
Array Example :
In the below program , we print all the elements on the screen.
Run
#include <iostream> using namespace std; int main () { int numbers[5] = { 17, 55, 76, 812, 735 }; cout << "The numbers are: "; for (const int &n:numbers) { cout << n << " "; } cout << "\nThe numbers are: "; for (int i = 0; i < 5; ++i) { cout << numbers[i] << " "; } return 0; }
Output :
The numbers are: 17 55 76 812 735 The numbers are: 17 55 76 812 735
Pointer Example :
Run
#include <iostream> using namespace std; int main() { int var1 = 93; int var2 = 84; int var3 = 67; cout << "Address of var1: "<< &var1 << endl; cout << "Address of var2: " << &var2 << endl; cout << "Address of var3: " << &var3 << endl; }
Output :
Address of var1: 0x7ffdbc9e38ec Address of var2: 0x7ffdbc9e38f0 Address of var3: 0x7ffdbc9e38f4
Pointer vs Array :
Till now, we understand what the array and pointer is. Lets see some basic difference between pointer and array in C++.
Pointers | Arrays |
---|---|
Value stored in the pointer can be changed. | Array is a constant pointer |
Pointer can’t be initialised at definition | Array can be initialised at definition. |
Used to allocate static memory | Used to allocate dynamic memory |
Increment is valid in pointer e.g, ptr++; | Increment is invalid in array e.g, a++; |
Example :
In the below program, we access the elements of array using pointers.
Run
#include <iostream> using namespace std; int main () { int arr[6] = { 21, 33, 65, 87, 59, 82 }; printf ("Elements of array : "); for (int i = 0; i < 6; ++i) { printf ("%d ", *(arr + i)); } return 0; }
Output :
Elements of array : 21 33 65 87 59 82
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment