简体   繁体   中英

Printing an array using a pointer which has the address to its first element

I was playing around making different programs to learn how a pointer, arrays and the name of an array are related. I was getting all the answers till this simple program gave me an unexpected output.

Here I have taken an array input through a function, returned the address of its first variable to a pointer and then tried to use the pointer to print the array.Some thing went wrong and I Didnt get the output i was hoping for. Can someone tell me whats wrong with my code?

#include<stdio.h>
#include<stdlib.h>

int n;      
int* InputArray()
{
printf("\nFucntion InputArray active\nPlease Enter the dimesnion (max 100): ");
scanf("%d",&n);
printf("\nAn array of %dx%d will be inputed and printed\n",n,n);

static int A[100][100];
int i=0,j=0;
for( i=0;i<n;i++)
{
printf("\n");
for( j=0;j<n;j++)
{printf("\nEnter the %d,%d element:",i,j);
 scanf("%d",&A[i][j]);
}


}

//view the array
i=0,j=0;
for( i=0;i<n;i++)
{
 printf("\n");
for( j=0;j<n;j++)
{printf("%d",A[i][j]);

}
}
return A;
}



int main()
{
int *AdrAry;
AdrAry=InputArray();
printf("\nDisplayig the array using its pointer declared ,"
"\nin the main\n");
int i,j;

printf("\n");

//Outputting array using pointer

for( j=0;j<n*n;j++)
printf("%d\t",*(AdrAry+j));

return 0;
}

I get the following output ( Observe the array output by the pointer not in sync with the declared array )

Fucntion InputArray active

Please Enter the dimesnion (max 100): 2

An array of 2x2 will be inputed and printed

Enter the 0,0 element:1

Enter the 0,1 element:2

Enter the 1,0 element:3

Enter the 1,1 element:4

12

34

Displayig the array using its pointer declared ,

in the main
1   2   0   0   

Your 2D array is 100 x 100, so when you use AdrAry+j you print the first line only. This should be:

for(i = 0; i < n; ++i)
  for(j = 0; j < n; ++j)
    printf("%d\t", *(AdrAry + (100 * i + j)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM