Converting a string of words of arbitrary size to an array of C strings

Hello!
I am working on the below program right now. I am asked to convert a string of words to char array. The libraries included are the only few that I can use. Since main function can not be altered, I have to return an allocated double pointer char array to match the 'free'. Basically, I need helps on the function called "words_array". Thank you guys so much for any helps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>//<cstring>
#include <cstdlib>

/**
 * Find number of words in s.
 * @param   count   number of words in s (separated by a space)
 * @param   sstream a string stream object
 * @param   l       a string that reads strings from stringstream
 * return   number of words in string s
 */
int words_of(std::string s) {
    int count = 0;
    std::string l;
    std::stringstream sstream(s);
    while (sstream >> l)    ++count;
    return count;
}

/**
 *  Convert string to character array of words.
 *  @param   s  string to convert
 *  @return     jagged array of words
 */
char **word_array(std::string s) {
    const char *array = s.c_str();
    char **charArray = (char**) malloc (sizeof(char) * (words_of(s)));
    strncpy(*charArray, array, sizeof(charArray));
    return charArray;
}

int main() {
    std::string files = "architecture.txt boolean.txt computers.txt kitties.txt";
    char **filenames = word_array(files);
    int n = words_of(files);
    for (int i=0; i<n; i++) {
        std::ofstream outfile(filenames[i]);
        outfile << "This is file " << i << std::endl;
        free(filenames[i]);
    }
    free(filenames);
    return 0;
}
Last edited on
Since main function can not be altered, I have to return an allocated double pointer char array to match the 'free'.

The fact that there are multiple frees in main should clue you in to something.
Topic archived. No new replies allowed.