0
void allocate(char string[])
{
    int nrCuv = 0, init_sz = strlen(string), counter = 0;
    char delim[] = "\n";

    for (int i = 0; i < strlen(string); i++)      //Here I calculated the number of words from the file
    {
        if (string[i] == "\n")
        {
            nrCuv += 1;
        }
    }

    nrCuv += 1;
    char *tablou[nrCuv];

    char *ptr = strtok(string, delim);
    while (ptr != NULL)                 //Here I tried to split the initial char into words
    {
        tablou[counter] = ptr;
        // printf("%s\n", ptr);
        ptr = strtok(NULL, delim);
        counter += 1;
    }

    for (int i = 0; i < nrCuv; i++)
    {
        puts(tablou[i]);
    }

}

The variable string has the contents of a file that has one word per line. I was trying to format the string variable so that I can access every word from within the tablou variable, like this

tablou[1] = "foo"

tablou[2] = "bar"

For some reason that I don't understand. it doesn't seem to work properly at all. Sometimes I get Segmenation Faults, sometimes it only prints the first word of the file. What am I doing wrong?

Leonard V.
  • 115
  • 1
  • 8
  • 3
    Also, in the loop that calls `puts`, it would be better to use `i < counter` as the terminating condition because `counter` might be less than `nrCuv` and only `counter` pointers have been set in `tablou[]`. – Ian Abbott Dec 14 '20 at 12:33
  • 3
    @JonGuiton This is C99's (and on) variable sized array, it is legal though limited (to the stack). – Yuri Feldman Dec 14 '20 at 12:52
  • Please [edit] and show a [mcve]. – Jabberwocky Dec 14 '20 at 13:12
  • 1
    `string[i] == "\n"` -> `string[i] == '\n'`, didn't you get at least a compiler warning? Othwerwise I don't see any obvious problems in your code. The problem most likely is in the calling code. See my previous comment and comply. – Jabberwocky Dec 14 '20 at 13:19
  • it worked changing `string[i] == "\n"` to `string[i] == '\n'`, though I got no errors/ warnings from the compiler – Leonard V. Dec 14 '20 at 15:14
  • What compiler do you have ? Be aware that `allocate("foo\nbar")` won't work. – Jabberwocky Dec 14 '20 at 15:26
  • @Jabberwocky I use gcc 9.3.0 . Indeed, `allocate("foo\nbar")` does not work. Are there any alternatives? – Leonard V. Dec 14 '20 at 15:44
  • 1
    @FusiFlag you cannot modify string literals. The alternative would be to make a copy of the string. Read this: https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-char-s-initialized-with-a – Jabberwocky Dec 14 '20 at 15:53

0 Answers0