One problem I see is that you need to move the line
if(currChar == '\n') currLine++;
inside the while loop.
I see a few more problems that I will be able to describe when I am on a full fledged computer, not a tablet.
Update
You have
char * fileToArray(char * filename){
int i;
int lineCount = getLineCount(filename);
char array[lineCount][MAX_ROW_LENGTH];
for(i = 1; i <= lineCount; i++){
strcpy(array[i], lineToString(filename, i));
//printf("%s\n", array[i]);
}
printf("%zu\n",sizeof(array));
return array;
}
Problems with this function:
The return value of
char*
is not compatible with the return statementreturn array;
.array
can be treated aschar (*)[MAX_ROW_LENTH]
, but notchar*
.Even if the return type and return statements were made to match, the main problem is that you are trying to return a pointer to an object that will be deleted when the function returns. The pointer will be invalid in the calling function.
The line
strcpy(array[i], lineToString(filename, i));
should be
strcpy(array[i-1], lineToString(filename, i));
since array indexing in C starts with
0
, not1
.
Other problems:
You are allocating memory for
string
inlineToString
but you are not deallocating it.You are allocating memory for
fileA
inmain
but you are not deallocating it.
The following versions of fileToArray
and main
worked with my testing. I tried keep your code as much possible and modified what I thought was absolutely essential.
void fileToArray(char * filename, int lineCount, char (*array)[MAX_ROW_LENGTH])
{
int i;
char* string;
for(i = 1; i <= lineCount; i++){
string = lineToString(filename, i);
strcpy(array[i-1], string);
free(string);
}
}
int main(int argc, char **argv)
{
int i;
int lineCount = getLineCount(argv[1]);
char array[lineCount][MAX_ROW_LENGTH];
fileToArray(argv[1], lineCount, array);
for(i = 0; i < lineCount; i++){
printf("%s\n", array[i]);
}
return 0;
}
PS The comments made by James R Matey in his answer are very valid. It's expensive to open and close a file just to get one line of text. I hope you find a way to incorporate his suggestions in your code.