Search code examples
arrayscpointersimplicit-conversionpointer-arithmetic

Printing 1D array using pointer in C


I want to print the data of array by using pointers so I try to save the address of array in the pointer. But the pointer doesn't print the data. I will print a second array as well later on so there are some extra variables declared.

Output: Output

Code

//print 1D array and 2D array
#include<stdio.h>
#include<stdlib.h>
int Arr1[10];
int Arr2[10][10];
int i, j, n1, n2;
int (*p1)[10];
int (*p2)[10][10];

int main()
{
    printf("For the 1D Array: \n");
    printf("Enter the number of elements you want to add: ");
    scanf("%d", &n1);

    printf("Enter the data for the elements:\n");
    for(i=0;i<n1;i++)
    {
        scanf("%d", &Arr1[i]);
    }
    printf("Displaying Array:\n");
    for(i=0;i<n1;i++)
    {
        printf("%d\t", Arr1[i]);
    }
    
    printf("\nDisplaying using pointer: \n");
    p1=Arr1;
    printf("1D Array is: \n");
    for(i=0;i<n1;i++)
    {
        printf("Arr[%d] is %d\t", i, *(p1[i]));
        printf("\nAddress of %d th array is %u\n", i, p1[i]);
    }

}

Solution

  • The pointer p1 is declared like

    int (*p1)[10];
    

    In this assignment statement

    p1=Arr1;
    

    the pointer is assigned with an expression of the type int * due to the implicit conversion of the array designator to pointer to its first element of the type int *.

    The pointer types of the operands are not compatible. So the compiler should issue a message.

    You could either write

    int (*p1)[10];
    
    //...
    
    p1 = &Arr1;
    printf("1D Array is: \n");
    for(i=0;i<n1;i++)
    {
        printf("Arr[%d] is %d\t", i, ( *p1 )[i] );
        printf("\nAddress of %d th array is %p\n", i,( void * ) ( *p1 + i ) );
    }
    

    The expression with the subscript operator

    ( *p1 )[i]
    

    is equivalent to

    *( *p1 + i )
    

    Or you could write

    int *p1;
    
    //...
    
    p1 = Arr1;
    printf("1D Array is: \n");
    for(i=0;i<n1;i++)
    {
        printf("Arr[%d] is %d\t", i, p1[i]);
        printf("\nAddress of %d th array is %p\n", i,( void * ) ( p1 + i));
    }
    

    I suppose that in the second call of printf you want to output the address of each element of the array..