[英]Printing an array using a pointer which has the address to its first element
我正在制作不同的程序,以學習指針,數組和數組名稱之間的關系。 我得到了所有答案,直到這個簡單的程序給了我意外的輸出。
在這里,我通過函數獲取數組輸入,將其第一個變量的地址返回給指針,然后嘗試使用指針來打印數組。有些事情出錯了,我沒有得到我想要的輸出。 有人可以告訴我我的代碼有什么問題嗎?
#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;
}
我得到以下輸出(觀察指針與聲明的數組不同步的數組輸出)
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
您的2D數組為100 x 100,因此當您使用AdrAry + j時,僅打印第一行。 應該是:
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.