Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

 C pointers & Arrays

Accessing one-dimensional array with pointer variable

We can assign the address of an array to a pointer variable.
After assigning the address of an array to a pointer, the pointer points to the first element of an array.

Example

C Programming Language Pointer to an Array

Previously we have seen how pointer is used to obtain value stored in the variable pointed by pointer.
Similarly, by using pointer variable, we can obtain any element of an array & its address.

Example

#include <stdio.h>
int main()
{
    int arr[5]={10,20,30,40,50};
    int *ptr=&arr[0];
    printf("\n Address of 0th element is %d",(ptr+0));
    printf("\n Address of 1st element is %d",(ptr+1));
    printf("\n Address of 2nd element is %d",(ptr+2));
    printf("\n Address of 3rd element is %d",(ptr+3));
    printf("\n Address of 4th element is %d",(ptr+4));
    printf("\n");
    printf("\n Value of 0th element is %d",*(ptr+0));
    printf("\n Value of 1st element is %d",*(ptr+1));
    printf("\n Value of 2nd element is %d",*(ptr+2));
    printf("\n Value of 3rd element is %d",*(ptr+3));
    printf("\n Value of 4th element is %d",*(ptr+4));
    return 0;
}

Output

Address of 0th element is 2293296, 2293296, 2293296
Address of 1st element is 2293300, 2293300, 2293300
Address of 2nd element is 2293304, 2293304, 2293304
Address of 3rd element is 2293308, 2293308, 2293308
Address of 4th element is 2293312, 2293312, 2293312

Value of 0th element is 10, 10, 10
Value of 1st element is 20, 20, 20
Value of 2nd element is 30, 30, 30
Value of 3rd element is 40, 40, 40
Value of 4th element is 50, 50, 50

 

Leave a reply