Difference between Arrays And Pointers in C++: As we have already learned about the arrays and pointers in the previous articles. Lets us know the difference between them.
Difference between Arrays And Pointers in C++
Pointers | Arrays |
---|---|
A pointer is a place in memory that points to the address of a variable. | An array is a single, pre-allocated chunk of contiguous elements (all of the same type), fixed in size and location. |
Pointer can’t be initialized at the definition | An array can be initialized at definition. Example: int num[] = { 2, 4, 5} |
A pointer is dynamic in nature. The memory allocation can be resized or freed later. | They are static in nature. Once the memory is allocated, it cannot be resized or freed dynamically. |
The assembly code of Pointer is different than Array | The assembly code of Array is different than Pointer |
The assembly code of Array is different than Pointer. | A pointer variable can store the address of the only variable |
When using the sizeof() operator on a fixed array, sizeof returns the size of the entire array (array length * element size) | When used on a pointer, sizeof returns the size of a memory address (in bytes) |
A fixed array knows how long the array it is pointing to | A pointer to the array does not know. |
The general form of declaring a pointer variable is: type *name; | General form for declaring a array is :type var_name[size]; |
Pointers Example:
#include <iostream> int main() { int x = 5; std::cout<< x <<'\n'; //print the value of variable x std::cout<< &x << '\n'; //print the memory address of variable x std::cout<< *(&x) << '\n';//print the value at the memory address of variable x (parenthesis not required, but make it easier to read) return 0; }
Output:
5
0x7ffd22feb9dc
5
Arrays Example
#include<iostream> using namespace std; int main() { int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array //traversing array for (int i: arr) { cout<<i<<"\n"; } }
Output:
10
0
20
0
30