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.