LearnFrenzy
Sign in Take a free test

Memory Allocation · Memory Programs · Question 3

Split a sentence into a heap array of words in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Return a heap-allocated array of heap-allocated words, plus a function that frees all of it.

Solution
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **split_words(const char *s, size_t *count) {
    size_t cap = 4, n = 0;
    char **words = malloc(cap * sizeof *words);
    if (words == NULL)
        return NULL;
    while (*s) {
        while (*s == ' ')
            s++;
        if (*s == '\0')
            break;
        const char *start = s;
        while (*s && *s != ' ')
            s++;
        size_t len = (size_t) (s - start);
        if (n == cap) {
            char **tmp = realloc(words, 2 * cap * sizeof *words);
            if (tmp == NULL)
                break;                              /* keep the words found so far */
            words = tmp;
            cap *= 2;
        }
        if ((words[n] = malloc(len + 1)) == NULL)
            break;
        memcpy(words[n], start, len);
        words[n][len] = '\0';
        n++;
    }
    *count = n;
    return words;
}

void free_words(char **w, size_t n) {
    for (size_t i = 0; i < n; i++)
        free(w[i]);                                 /* the strings first ... */
    free(w);                                        /* ... then the array */
}

int main(void) {
    size_t n;
    char **w = split_words("  the quick  brown fox jumps ", &n);
    if (w == NULL)
        return 1;
    for (size_t i = 0; i < n; i++)
        printf("[%s] ", w[i]);
    printf("\n%zu words\n", n);
    free_words(w, n);
    return 0;
}

Output Verified by compiling and running

[the] [quick] [brown] [fox] [jumps]
5 words

Two levels of ownership: the array of pointers and each word. The pointer array grows with realloc() (5 words need a resize from 4 to 8), and free_words() releases everything in the right order.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links