How would I go about dynamically allocating memory to char** list in this function?
Basically the idea of this program is I have to read in a list of words from a file. I cannot assume max strings or max string length.
I have to do other stuff with the C-strings but that stuff I should be fine with.
Thanks!
void readFileAndReplace(int argc, char** argv)
{
FILE *myFile;
char** list;
char c;
int wordLine = 0, counter = 0, i;
int maxNumberOfChars = 0, numberOfLines = 0, numberOfChars = 0;
myFile = fopen(argv[1], "r");
if(!myFile)
{
printf("No such file or directory\n");
exit(EXIT_FAILURE);
}
while((c = fgetc(myFile)) !=EOF)
{
numberOfChars++;
if(c == '\n')
{
if(maxNumberOfChars < numberOfChars)
maxNumberOfChars += numberOfChars + 1;
numberOfLines++;
}
}
list = malloc(sizeof(char*)*numberOfLines);
for(i = 0; i < wordLine ; i++)
list[i] = malloc(sizeof(char)*maxNumberOfChars);
while((c = fgetc(myFile)) != EOF)
{
if(c == '\n' && counter > 0)
{
list[wordLine][counter] = '\0';
wordLine++;
counter = 0;
}
else if(c != '\n')
{
list[wordLine][counter] = c;
counter++;
}
}
}
Do like this:
Additionally, if you are allocating memory dynamically. you are to free it as work done:
EDIT
In you revised question:
wordLineandcounterare0before this code:
you have to assign value to
wordLineandcountervariableAlso memory allocation should be before the following loop(outside):
EDIT:
New your third version of question. You are reading file two times. So you need to fseek(), rewind() to first char before second loop starts.
try with:
also I have doubt in your logic to calculate
numberOfLinesandmaxNumberOfChars. please check that alsoEDIT
I think your calculation for
maxNumberOfChars = 0, numberOfLines = 0is wrong try like this:maxNumberOfCharsis max number of chars in a line.Also change code: