Pointer vs 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 <stdio.h> int main() { int arr[5] = {1,3,6,8,9}; printf("The elements of array are :"); for(int i=0;i<5;i++){ printf("%d ", arr[i]); } return 0; }
Output :
The elements of array are :1 3 6 8 9
Pointer Example :
Run
#include <stdio.h> int main() { int val = 40; int* pointer; // declaration of pointer pointer = &val; printf("1. Value at pointer = %p \n", pointer); printf("2. Value at val = %d \n", val); printf("3. Value at *pointer = %d \n", *pointer); return 0; }
Output :
1. Value at pointer = 0x7fff0bf90d7c 2. Value at val = 40 3. Value at *pointer = 40
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 <stdio.h> int main() { int arr[6] = {1,3,5,7,9,12}; printf("Elements of array : "); for (int i = 0; i < 6; ++i){ printf("%d ", *(arr + i)); } return 0; }
Output :
The elements of array are :1 3 6 8 9
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