I am trying to create a program which does:
- Find the length of the largest word, the lines & the number of letters
- Store the data from a file to string (
str) - Store the data from string (
str) to a dynamic allocated array
text:link
My program does not store the words in the array
I used a debugger link and I notice that the problem was in str variable (error reading variable str (value requires 146297 bytes more than max value - size) What does that mean and how could I fix it?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
FILE *fp;
fp = fopen("C:\\Downloads\\AlicesAdventuresInWonderland.txt", "r+");
if (fp == NULL)
{
printf("cannot open the file\n");
exit(8);
}
char ch;
int len = 0, counter = 0, thelongest = 0, letters = 0, i = 0, j = 0, k = 0;
for (;;)
{
ch = fgetc(fp);
letters++;
if (ch == '\n' || ch == EOF)
{
if (thelongest < len)
{
thelongest = len;
}
if (len > 0)
{
counter++;
}
len = 0;
if (ch == EOF)
{
break;
}
}
else
{
len++;
}
}
printf("the number of lines is : %d", counter);
printf("\nthe length of the longest word is : %d", thelongest);
printf("\nthe number of letters is %d", letters);
char str[letters + 1];
rewind(fp);
char **arr;
arr = (char **)malloc(sizeof(char*) * (letters + 1));
for (ch = fgetc(fp); ch != EOF; ch = fgetc(fp))
{
if (!ispunct(ch))
{
str[i++] = ch;
}
}
str[i]= '\0';
rewind(fp);
i = 0, k = 0, j = 0;
char tempstr[thelongest + 1];
for (;;)
{
if (str[k] == '\n' || isspace(str[k]) || str[k] == '\0')
{
if (k != 0)
{
tempstr[k] = '\0';
arr[j++] = strdup(tempstr);
k = 0;
}
if (tempstr[k] == '\0')
{
break;
}
}
else
{
tempstr[k++] = str[i++];
}
}
arr[j] = NULL;
for (i = 0; i < counter + 1; i++)
{
printf("\n the words are %s", arr[i]);
}
return 0;
}