![](/img/trans.png)
[英]My C function recurses over system directories and segfaults over large inputs. How can I fix this?
[英]I m trying to build a 2*2 array but my program asks for 5 inputs. Why?
我無法將輸入語句中錯過的位置歸零。 我已經建立它來獲取四個值作為輸入,但它又增加了一個。
操縱數組項以檢查是否存儲了第五個值。 基本的東西
#include <stdio.h>
int main()
{
int i,j,a[2][2];
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
scanf("%d\t",&a[i][j]);
}
printf("\n%d\t%d\n%d\t%d", a[1][1],a[1][2],a[2][1],a[2][2]);
}
您已經聲明了
int a[2][2];
其中有四個項, a[0][0]
, a[0][1]
, a[1][0]
和a[1][1]
。
但是,您將從1
開始建立索引,然后上升到2
,因此超出了未定義行為的范圍。 任何事情都可能發生。
更改循環,即:
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
// as you were
從0開始索引。
您還需要考慮您的printf
語句,因為這也會超出要求。
#include <stdio.h>
int main()
{
int i,j,a[2][2];
for(i=0;i<2;i++) /*go through rows - arrays in c go [0- (n-1)]*/
{
for(j=0;j<2;j++)/*go through col */
scanf("%d",&a[i][j]); /*remove \t- now will scan 4 values only */
}
printf("\n%d\t%d\n%d\t%d", a[0][0],a[0][1],a[1][0],a[1][1]);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.