0

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.

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Do you mean i need to go back to the start of a file before loops? And how can i make it? And thanks -- all other things i changed.
@DimaReshetnikov Look into fseek or rewind.
Do i need fseek() function to set position to the beginning of a file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.