The below code is a snippet from my solution to the hacker rank problem- https://www.hackerrank.com/challenges/querying-the-document/problem
The code works, but during debugging, I am getting segmentation error in line 19,20 and printing NULLLLLL, when the code reaches 'C' in "Learning C...". I do not understand why.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char ****get_document(char *text)
{
int para = 0, sen = 0, word = 0, alph = 0;
char c, ****doc = (char ****)calloc(1, sizeof(char ***));
*doc = (char ***)calloc(1, sizeof(char **));
**doc = (char **)calloc(1, sizeof(char *));
for (int i = 0; i < strlen(text); i++)
{
c = text[i];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
{
(*(*(*(doc + para) + sen) + word)) = (char *)realloc((*(*(*(doc + para) + sen) + word)), sizeof(char) * (alph + 1));
if (((*(*(*(doc + para) + sen) + word))) == NULL)
printf("NULLLLLLLLLLL"); // checking whether memory is given or not.
(*(*(*(*(doc + para) + sen) + word) + alph)) = c;
alph++;
}
else if (c == ' ')
{
*(*(*(doc + para) + sen) + word) = (char *)realloc((*(*(*(doc + para) + sen) + word)), sizeof(char) * (alph + 1));
*(*(*(*(doc + para) + sen) + word) + alph) = '\0';
alph = 0;
word++;
*(*(doc + para) + sen) = (char **)realloc((*(*(doc + para) + sen)), sizeof(char *) * (word + 1)); // memory for word.
}
}
return doc;
}
void main()
{
char text[] = "Learning C is fun.", ****d;
d = get_document(text);
}