PoorProgrammer3 PoorProgrammer3 - 5 months ago 33
C Question

How to store each sentence as an element of an array?

So, suppose I have an array (program asks me to write some text):

char sentences[] = "The first sentence.The second sentence.The third sentence";

And I need to store each sentence as an array, where I can have access to any word, or to store the sentences in a single array as elements.
(sentences[0] = "The first sentence"; sentences[1] = "The second sentence";)

How to print out each sentence separately I know:

char* sentence_1 = strtok(sentences, ".");
char* sentence_2 = strtok(NULL, ".");
char* sentence_3 = strtok(NULL, ".");

printf("#1 %s\n", sentence_1);
printf("#2 %s\n", sentence_2);
printf("#3 %s\n", sentence_3);

But how to make program store those sentences in 1 or 3 arrays I have no idea.
Please, help!


If you keep it in the main, since your sentences memory is static (cannot be deleted) you can simply do that:

#include <string.h>
#include <stdio.h>

int main()
  char sentences[] = "The first sentence.The second sentence.The third sentence";
  char* sentence[3];
  unsigned int i;

  sentence[0] = strtok(sentences, ".");

  for (i=1;i<sizeof(sentence)/sizeof(sentence[0]);i++)
    sentence[i] = strtok(NULL, ".");

  for (i=0;i<sizeof(sentence)/sizeof(sentence[0]);i++)
    printf("%d: %s\n",i,sentence[i]);

  return 0;


In the general case, you first have to duplicate your input string:

char *sentences_dup = strdup(sentences);
sentence[0] = strtok(sentences_dup, ".");

many reasons for that:

  • you don't know the lifespan/scope of the input, and it is generally a pointer/a parameter, so your sentences could be invalid as soon as the input memory is freed/goes out of scope
  • the passed buffer may be const: you cannot modify its memory (strtok modifies the passed buffer)
  • change sentences[] by *sentences in the example above and you're pointing on a read-only zone: you have to make a copy of the buffer.

Don't forget to store the duplicated pointer, because you may need to free it at some point. Another alternative is to also duplicate there:

  for (i=1;i<sizeof(sentence)/sizeof(sentence[0]);i++)
    sentence[i] = strdup(strtok(NULL, "."));

so you can free your big tokenized string at once, and the sentences have their own, independent memory.