I am trying to create a program which :
- finds the word with largest length from a file
- creates a dynamically allocated 2d array
- stores the words from the file to array
https://gist.github.com/up1047388/363854cbe703a6f297ebb644c50d307f (the whole program)
the file: https://gist.github.com/up1047388/758574c484d916c4aeba106f293f185a
The problem is in this loop (I used printf
as a hint to find the problem but the program does not print anything inside the problem):
That's I am trying to do in the loop is the following :
- pass the character which has every line of the file in a string
- when the program reads the
'\n'
from the file stores the word which is stored in the string to the array
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
fp = fopen("C:\\Users\\Docs\\lol.txt", "r");
if (fp == NULL)
{
printf("the file is empty");
exit(8);
}
int length[4];
int ch1;
int counter1 = 0, i = 0;
while ((ch1 = getc(fp)) != EOF)
{
if (ch1 == '\n')
{
length[i] = counter1;
i++;
counter1 = 0;
continue;
}
counter1++;
}
length[i] = counter1;
fseek(fp, 0, SEEK_SET);
int thelongest = length[0];
for (i = 0; i < counter; i++)
{
if (length[i] >= thelongest)
{
thelongest = length[i];
}
}
printf("\n the longest number is %d", thelongest);
char **arr;
**arr = (char **)malloc(sizeof(char *) * 4);
int j = 0 i = 0;
char str[thelongest];
int ch2;
while ((ch2 = getc(fp)) != EOF)
{ // printf("fvfdvdfvd");
if (ch2 == '\n')
{
arr[j] = (char *)malloc(thelongest * sizeof(char));
strcpy(arr[j], str);
// printf("\n%c",str[i]);
j++;
continue;
}
str[i] = ch2;
i++;
}
str[i] = ch2;
strcpy(arr[j], str);
return 0;
}