Pointer and Array in C Program.
Hello Everyone,
Today we will discuss about Pointer and Array in C Program. I recommend you to refer my below blogs before starting this topic.
https://dheeraj60.blogspot.com/2020/06/array-and-its-beneifts-in-c-program.html
https://dheeraj60.blogspot.com/2020/06/multi-dimensional-array2d-and-3d-in-c.html
https://dheeraj60.blogspot.com/2020/06/basic-concept-of-pointer-in-c-and-its.html
https://dheeraj60.blogspot.com/2020/06/pointer-to-pointer-in-c-program-dotcmdb.html
As we already know An array is a block of sequential data and Pointer used to get the variable address. So understand the below Program where we print the address of Array elements by using pointer.
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int *p;
int print[4] = { 10, 11, 12, 13} ;
p = &print[0];
for ( int i = 0 ; i<4 ; i++ )
{
printf("print[%d]: value is %d and address is %p\n", i, *p, p);
p++;
}
return 0;
}
Here we use Pointer variable as int *p and declaring the array print[4] with integer numbers , after that Assigning the address of print[0] to the pointer as p = &print[0] because array name represents the address of the first element and finally Incrementing the pointer so that it points to next element by using p++ on every increment.
Note: Array always starts with 0 so here 1st value will treat from 0 only There is a difference of 4 bytes between each element because that’s the size of an integer. This means all the elements are stored in consecutive contiguous memory locations in the memory.
Below is the output of above Program in Compiler Code Block with both values and address.
You can see the output of value with address in Hexadecimal Format.
Let’s understand with another Program by using Pointer and Array.
#include<stdio.h>
#include<stdlib.h>
int main() {
int i[4] = {1, 2, 3, 4};
int* p;
p = &i[2];
printf("value for pointer *p for position 3 = %d \n", *p);
printf(" value for pointer *(p+1) for position 4 = %d \n", *(p+1));
printf(" value for pointer *(p-1) for position 1 = %d", *(p-1));
return 0;
}
Here pointer p is assigned the address of the third element as I used p = &i[2]; and we know array starts with 0 . Here we use pointer to display the value as per position by using increment and decrement in printf for value.
Below is the output of above program in compiler Code block for your understanding.
Here you can see the value element is displayed by pointer by using array for elements.
Hope you are able to understand how to use Pointer in Array Program. Please read this blog carefully and try to write more programs by using Pointers in Array and let me know if you have any doubts. Play with Pointer and Array as much as you can. In next blog I will come up with next topic.
Thanks
Well explained !
ReplyDelete