So I have a function called scanCode which scans words from a text file and stores it in a 2D array. I then want to return this array into an array variable in the main function, this is my code so far
#include <stdio.h>
char **scanCode()
{
FILE *in_file;
int i = 0;
static char scan[9054][6];
in_file = fopen("message.txt", "r");
while (!feof(in_file))
{
fscanf(in_file, "%s", scan[i]);
i++;
}
return scan;
}
int main(void)
{
int hi[9053];
FILE *in_file;
in_file = fopen("message.txt", "r");
char **array = scanCode();
printf("%c", array[0]);
printf("%c", array[1]);
printf("%c", array[2]);
printf("%c", array[3]);
}
So basically the array returned from the scanCode function I want it to be stored in the char array in the main function.. after looking at a lot of questions and answers here, this is what I got to but the pointer etc is hard to understand for me.. could someone tell me what I did wrong here?
%cto print a string,array[n]?message.txtfile that are longer than 5 characters? And why did you open the file twice (once inmainand once in the function)? That's a bad idea.while (!feof(in_file))is a bad way to read until end of file.feofwill only be true on an attempt to read beyond end of file, so your code will attempt an additionalfscanfafter the last line of the file has already been read, and you'll have one bogus entry at the end of your scan array. See Why is “while ( !feof (file) )” always wrong?.while (feof() ...Perhaps this 4th one will do the trick.