0

i am getting segmentation error(core dumped)on the following code :-

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char text[100];

    int max = 0,ctr = 0;
    int j=0;
    printf("Enter the text: ");
    gets(text);
    int tokens = 1;
    for (int i =0; text[i] != '\0'; i++)
    {
        if (text[i] == ' ')
            tokens ++;

        ctr = 0;

        while (text[j] != ' ')
        {
            ctr ++;
            j++;
        }

        if (max < ctr)
            max = ctr;
        j++;
    }
    int r,c,p=0;
    r = malloc(sizeof(char)*tokens);
    c = malloc(sizeof(char)*max);
    char token[r][c];
    for (int k = 0; text[k] != '\0'; k++)
    {
        if (text[k] = ' ')
        {
            p++;
            continue;
        }
        token[p][k] = text[k];

    }

    for (int k = 0;k < r; k++)
    {
        for (int z=0; z<c; z++)
            printf(" %c",token[k][z]);
        printf("\n");
    }

    return 0;
}

The question is :-

Given multiple lines of text, parse the text to separate the tokens. A token is a word separated by a space. Store the tokens as individual strings whose maximum length is unspecified. Maintain a one-dimensional array of pointers pointing to each string. Let the length of 1D array depend upon the number of tokens. Also the memory allocation for each token should depend upon the number of characters in each token.

  • 2
    *...individual strings whose maximum length is unspecified.* This might be a good example of: [Why is the `gets` function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) Without knowing the exact input, that's the first obvious cause. – Weather Vane Apr 10 '20 at 14:23
  • You code generates 3 warnings that might be contributing to the problem. On lines 31, 32, and 36. The real problem is line 36 with the `=` operator. You are using the assignment operator instead of the equality operator. – Jeff Holt Apr 10 '20 at 14:24
  • `r = malloc(sizeof(char)*tokens);` and the next lines to `char token[r][c];` show a misunderstanding about memory allocation. – Weather Vane Apr 10 '20 at 14:25

0 Answers0