split string into lines
I want to split a string by "\n" and add to an array only lines which
contain a specific token.
I have this code:
char mydata[100] = "mary likes apples\njim likes playing\nmark hates
school\nanne likes mary";
char *token = "likes";
char ** res = NULL;
char * p = strtok (mydata, "\n");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
if (strstr(p, token))
res[n_spaces-1] = p;
p = strtok (NULL, "\n");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = '\0';
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
I get:
res[0] = mary likes apples
res[1] = jim likes playing
Segmentation fault
How can I split that string correctly? Is there any other way of doing
that except strtok?
No comments:
Post a Comment