Problem STRTOK 2D ARRAY

Write your question here.
So i have created a 2d array with malloc and I m trying to STRTOK a file and put the words in the array.I managed to do that but for some reason when i use printf ,it prints the words but it continues forever in a for loop


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  #include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define WIDTH 50

int main()
{
    /**/
    char  **wordarr, *wordpc ;
    int option=1, library, howmany, i,number, numwords=0;

    wordarr = (char**)malloc(sizeof(char*) * howmany);
    for(i = 0; i<howmany; i++){
        wordarr[i] = (char*)malloc(sizeof(char) * WIDTH);
    }
    //bazw tis le3eis apo to arxeio sto pinaka
    FILE *fp;
    fp = fopen("file.txt", "r");
    if (fp == NULL) {
        fprintf(stderr, "File not found\n");
        exit(1);
    }
    char buffer[10000];
    fgets(buffer, 10000, fp);

    char *tok;
    i=0;
    tok = strtok(buffer, " .,!");
    while (tok != NULL) {
        /*if (i >= howmany) {
            howmany *= 2;
            wordarr = (char**)realloc(wordarr, sizeof(char*) * howmany);
            for (i=howmany/2; i<howmany; i++) {
               wordarr[i] = (char*)malloc(sizeof(char) * WIDTH);
            }
            printf("realloc\n");
        }*/
        strcpy(wordarr[(i)++], tok);
        tok = strtok(NULL, " .,!");
    }

    fclose(fp);

    for (i=0; i<howmany; i++) {
        printf("[%s]\n", wordarr[i]);
    }


    //
    for (i=0; i<howmany; i++) {
        free(wordarr[i]);
    }
    free(wordarr);
You should pay attention to the warnings your compiler is giving you.

In this case, it will be warning you that you're trying to use the value of howmany, without having initialised that variable. This leads to undefined behaviour.
Oh thanks dude didnt notice fuqing blind .Do you know how can i make my array to be big enough as are the words in the file???thanks
Allocate the memory for the array after you know how many words you have.

Or, more sensibly, stop using arrays (and C-style allocation), and use vectors instead, so that all the memory management is done for you automatically.
Topic archived. No new replies allowed.