1

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]);
    }

}
2
  • Arr1 IS the address of the array! printf("Arr[%d] is %d\t", i, *(Arr1+i)) works Commented Nov 26, 2022 at 11:11
  • You need the address p1=&Arr1; also to print use printf("Arr[%d] is %d\t", i, (*p1)[i]); and printf("\nAddress of %d th array is %p\n", i, *p1+i); Commented Nov 26, 2022 at 11:46

1 Answer 1

0

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..

Sign up to request clarification or add additional context in comments.

2 Comments

Okay, I see the mistake in the incompatibility of pointer types. Yes, I wanted to print the address of each element in the array. What is the purpose of using ( void * ) ?
@L127Bangtanned The argument of the conversion specifier p shall be a pointer of the type void *.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.