Bar
Bar

Reputation: 351

reading from file and pass to a two dimensional array in C

I want to read a text file and put it's data into a 2 dimensional array. This code works for a small text file like 0 1 1 1 0 1 1 0 1 1 1 1 but gives segmentation fault for a big text file and 648x512 array. What could be the problem? What could be a better code for doing this?

Link to a large txt file:

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;

        }
    }
}

Upvotes: 2

Views: 7057

Answers (2)

Ben Brammer
Ben Brammer

Reputation: 998

because you're using too much stack space. Main will need a stack big enough to hold M, which will take 512x648x(sizeof(int)). Assume a 4 byte int, that's 1327104 bytes just for one variable. Depending on your environment, that's a lot. If you are going to use more than a little memory, dynamically allocated it:

int M[] new int[C*R] or int M[][] = new int[C][R] (same diff, the first one is actually easier to work with)

Cheers

Upvotes: 2

taocp
taocp

Reputation: 23634

When the array size is large, for example: 648x512, M[R][C] used out all stack space of your program, therefore, you get segmentation fault.

Try to use dynamic array instead and remember to release it after use.

int** M= new int*[R];
for(int i = 0; i < R; ++i)
    M[i] = new int[C];

Upvotes: 2

Related Questions