[英]stack & buffer overrun in arrays c language
好吧,我是C語言編程的新手,並且不熟悉緩沖區和堆棧的主題..任何人都可以找出問題的原因..謝謝,
這是我的程序..首先我遇到運行時錯誤
“變量'arr2'周圍的堆棧已損壞”
然后當我推動繼續時,這東西出現
“ arr2.exe中發生了緩沖區溢出,這已破壞了程序的內部狀態。按Break調試程序或繼續終止程序。”(arr2是我的程序名)
這是我的源代碼(Microsoft Visual Studio 2010)(C語言),該程序僅用於讀取兩個數組的元素
#include <stdio.h>
#include <conio.h>
int main()
{
int arr1[2][2] , arr2[2][2];
int i,j;
/* to read the elements of first array */
printf("enter the elements of the first matrix\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("enter the number[%d][%d]",i+1,j+1);
scanf("%d",&arr1[i][j]);
}
}
/* to read the elements of the second array */
printf("enter the elements of the seconf matrix\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("enter number[%d][%d]",i+1,j+1);
scanf("%d",&arr2[i][j]);
}
}
return 0;
}
始終牢記索引從零開始,所以這是錯誤的:
for(i=0;i<=2;i++)
它應該是
for(i=0;i<2;i++)
其他循環也一樣。
在C中,數組從0
索引。 循環
for(i=0;i<=2;i++)
和
for(j=0;j<=2;j++)
將填充通過數組。
這些for循環會導致您出錯:
for(j=0;j<=2;j++)
您將嘗試訪問未定義的arr1[i][2]
(也適用於i> = 2)。 由於您使用以下形式聲明了數組: int arr[2][2]
,因此需要此for循環:
for(j = 0; j < 2; j++) // Same for i : for(i = 0; i < 2; i++)
您所有的for
循環可能都不正確(因為聲明t[2]
數組時索引應為0或1)。 <=
應該是<
,例如
for(i=0;i<2;i++)
並且請學習如何 使用調試器 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.