i'm trying to fill each row of the array with each word of the file.
I don't want to overallocate memory , so i want to know atleast the lenght of the longest word and the number of rows i should allocate, so the number of words written in the file.
I can't understand where is the problem in the code. I think it should be a problem with counting the longest word since when i print longest\_file\_word after assigning the value returned by the function it prints -1.

Obviously it doesnt work.

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int longestWord(char *file, int *nWords);
char ** Create2DStr(ssize_t numStrings, ssize_t maxStrLen);

int main(int argc, char *argv[]){
    int  file_elements_number=0 , i , j , k , z , longest_file_word , count_file_words ;
    char *filename =(char*)malloc((strlen(argv[2]) +1 )*sizeof(filename));
    strcpy( filename , argv[1]);
    for(i  =  0; i < strlen(argv[1])+1 ; i++){
        printf("%c" , filename[i]);
    }
    if(filename = NULL){
        printf("Non c'e' abbastanza memoria");
        return 1;
    }
    if(argc!=2)
    {
        printf("Errore numero parametri passati da linea di comando\n");
        return 1;
    } 
    longest = longestWord( filename , &count);
    printf("ciao %d\n%d\n", count , longest);
    char **file_words = Create2DStr(count, longest);
    FILE *file_ptr;

    const char delim[] = {" \n\t"};
    char line[260];
    char *buf = NULL;

    file_ptr = fopen( filename, "r");
    count=0;
    while(fgets(line, 260, file_ptr))
    {
        buf = strtok(line, delim);
        while(buf)
        {    
            if((strlen(buf) > 0)){
                strcpy(file_words[count], buf);
                count++;
            }
            buf = strtok(NULL, delim);
        }
    }
    for(i = 0 ; i < count ; i++){
         for( j = 0 ; j < longest ; j++){
             printf("%c" , file_words[i][j]);
         }
         printf("\n");
    }

    fclose(file_ptr);    
    free(filename);
    filename = NULL;
    return 0;

}

int longestWord(char *filename, int *nWords)
{
    FILE *file_ptr=0;
    int cnt=0, longest=0, numWords=0;
    char c;
    file_ptr = fopen(filename, "r");
    if(file_ptr){
        while ( (c = fgetc(file_ptr) ) != EOF )
        {
            if ( isalnum (c) ) {
                cnt++;  
            }
            else if ( ( ispunct (c) ) || ( isspace(c) ) || (c == '\0' ) || (c== '\n'))
            {
                (cnt > longest) ? (longest = cnt, cnt=0) : (cnt=0);
                numWords++;
            }
        }
        *nWords = numWords;
        fclose(file_ptr);
    }
    else {
        return -1;
    }

    return longest;
}

char ** Create2DStr(ssize_t numStrings, ssize_t maxStrLen){
    int i;
    char **a = {0};
    a =(char**) calloc(numStrings, sizeof(a));
    for(i=0;i<numStrings; i++)
    {
        a[i] = (char*)calloc(maxStrLen + 1, 1);
    }
    return a;
}

```