[英]reading from file and pass to a two dimensional array in C
我想讀取一個文本文件,並將其數據放入二維數組中。 此代碼適用於像0 1 1 1 1 1 1 1 0 1 1 1 1 1這樣的小型文本文件,但對於大型文本文件和648x512數組會產生分段錯誤。 可能是什么問題呢? 這樣做有什么更好的代碼?
鏈接到大型txt文件:
http://mimoza.marmara.edu.tr/~omer.korcak/courses/CSE246%20-%20Spring2012/squares.txt
#include<stdio.h>
FILE *input;
int x=0, y=0, R=0, C=0,c=0;
int main()
{
input = fopen("squares.txt", "r");
C = 512;
R = 648;
int M[R][C];
for(x = 0; x < R; ++x ) {
for(y = 0; y < C; ++y ) {
fscanf( input, "%d", &c );
M[x][y]=c;
}
}
}
當數組大時,例如: 648x512, M[R][C]
用完程序的所有堆棧空間,因此會出現分段錯誤。
嘗試改用動態數組,並記住在使用后釋放它。
int** M= new int*[R];
for(int i = 0; i < R; ++i)
M[i] = new int[C];
因為您使用了太多的堆棧空間。 Main需要一個足夠大的堆棧來容納M,這需要512x648x(sizeof(int))。 假設一個4字節的int,僅一個變量就是1327104字節。 根據您的環境,這很多。 如果要使用更多的內存,請動態分配它:
int M [] new int [C * R]或int M [] [] = new int [C] [R](與diff相同,第一個實際上更易於使用)
干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.