Table of Contents
C pointers and array
Array is an ordered collection of the same type of elements which are stored in contiguous memory locations and these elements can be accessed using indices of an array.
Like all the primitive data types, pointers can also store the address of an array.
In an array if we check the address of the whole array and the first element of the array then we will see that it is the same.
Let's take an example
#include <stdio.h>
int main ()
{
int nums[]={1,2,3,4,5};
printf("n &nums = %d",&nums);
printf("n &nums[0] = %d",&nums[0]);
return 0;
}
Output :
&nums = 6422300
&nums[0] = 6422300
Above example shows that the address of the first element of an array and address of the whole array is the same.
If we store the address of any element of an array or address of an array in pointer then we can traverse through the entire array.
Pointer can shift from one element to another of an array by using some arithmetic operators and increment/decrement operators.
We know that array elements are stored in contiguous memory locations and the size of each block is dependent on data types of the array.
When we store the address of an array in pointer we can shift pointer forward using ++ or +1 and we can shift pointer backward using — or -1.
For storing address of an array there is no need to use “& address operator” but if we want to store address of any particular element of an array then we need “& address operator”.
Example of pointers with array in C
#include <stdio.h>
int main ()
{
int nums[]={1,2,3,4,5};
//storeing address of an array
int *ptr = nums;
//Printing the value which stored in the address which is stored in ptr
//ptr is pointing to 0th element of array
printf("n *ptr = %d",*ptr);
/*
Incrementing pointer's value using pre-increment operator
This will make ptr to shift forward and store
address of next element of an array
now pointer will point to index 1 of an array
*/
printf("n *(++ptr) = %d",*(++ptr));
/*
Incrementing ptr by 2 means it will now
ptr will point to index 3 of an array
*/
printf("n *(ptr+2) = %d",*(ptr+2));
return 0;
}
Output :
*ptr = 1
*(++ptr) = 2
*(ptr+2) = 4
CHECKOUT OTHER RELATED TOPICS
CHECKOUT OTHER QUIZZES
Quizzes on Operator |
Easy Quiz on Operators in C part 1 |
Easy quiz on operators in C part 2 |
Easy quiz on operators in C part 3 |
Quizzes on Loops |
Easy quiz on loops in C part 1 |
Easy quiz on loops in C part 2 |
Easy quiz on loops in C part 3 |
Quizzes on Decision Making Statement |
Easy Quiz On Decision Making Statements Part 1 |
Easy Quiz On Decision Making Statements Part 2 |
Quizzes on String |
Easy quiz on String in C programming part 1 |
Quizzes on Array |
Easy quiz on Array in C programming – part 1 |
5 – Best Java program to convert decimal to binary |
New Quizzes Coming soon.. |
PRACTICALS IN C PROGRAM
