简体   繁体   English

使用指向第一个元素的地址的指针打印数组

[英]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. 您的2D数组为100 x 100,因此当您使用AdrAry + j时,仅打印第一行。 This should be: 应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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