Dima R.
Dima R.

Reputation: 1

Difficulties reading a contents of text file into 2*2 array

I encountered some difficulties reading a chars from a text file into a two-dimensional dynamic array -- it fails with "Unhandled exception at 0x011d155d in Problem_03_life.exe: 0xC0000005: Access violation writing location 0xfdfdfdfd."

Here is a code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]){

if(argc <= 1) printf("Program needs two arguments: input file and output file!");

FILE* f;
f = fopen(argv[1],"r");
if(f == NULL) printf("File cannot be opened!\n");


/* Determining how many lines and length of string */ 
int m = 0;
int n = 0;
char c;
while((c = fgetc(f))!=EOF) {
    if(c == '\n') {n++;}
    else m++;
}
m /= n; // counting quantity of chars in one line

/* here i'm allocating memory for array (am i right?) */ 
char** field = (char**)malloc(n*sizeof(char*));
for(int i = 0; i < n; i++) {
    *(field + i) = (char*)malloc(m*sizeof(char));
} 

int i = 0, j = 0;


for(i = 0; i <= n; i++){
    for(j = 0; j <= m; j++){
        *(*(field + i)+ j) = fgetc(f); // Here i get an error
    }
}

fclose(f);

}

Here is a contens of a file (i need to read white spaces too):

*************
* ##        *
*           *
* #         *
*************

What am i doing wrong using a ponters to read into it?

Thank you.

Upvotes: 0

Views: 77

Answers (1)

cnicutar
cnicutar

Reputation: 182649

There's more than one problem with your code:

  • The second for goes "one-too-far". Change "<=" to "<"
  • You're depending on the fact that each line has the same length. Once different lines have different lengths you'll run into trouble
  • You're using a char to store the return value of fgetc. fgetc returns int
  • You're trying to call fgetc after it already returned EOF. By definition it can only return fgetc. You need to rewind or consider a different strategy

Also, you're making it harder than it has to be:

  • *(field + i) can be written as field[i]
  • *(*(field + i)+ j) can be written as field[i][j]

Upvotes: 1

Related Questions