1 #include <stdlib.h>
2 #include <string.h>
3 #include "str.h"
4 #include "striter.h"
5 #include "envstr.h"
6
7 /** Make a \c environ compatable array of pointers to the environment
8 * string.
9 * \note The returned pointer is dynamically allocated, and must be
10 * freed. */
envstr_make_array(const struct str * env)11 char** envstr_make_array(const struct str* env)
12 {
13 striter i;
14 int count;
15 char** array;
16 for (striter_start(&i, env, 0), count = 0;
17 striter_valid(&i);
18 striter_advance(&i), ++count)
19 ;
20 array = malloc((count + 1) * sizeof *array);
21 for (striter_start(&i, env, 0), count = 0;
22 striter_valid(&i);
23 striter_advance(&i), ++count)
24 array[count] = (char*)i.startptr;
25 array[count] = 0;
26 return array;
27 }
28
29 #ifdef SELFTEST_MAIN
30 MAIN
31 {
32 static const str env = {"A=1\0B=2\0C=3\0", 12, 0};
33 char** e;
34 int i;
35 e = envstr_make_array(&env);
36 for (i = 0; e[i] != 0; ++i) {
37 obuf_puti(&outbuf, i);
38 obuf_putc(&outbuf, ':');
39 obuf_puts(&outbuf, e[i]);
40 obuf_endl(&outbuf);
41 }
42 }
43 #endif
44 #ifdef SELFTEST_EXP
45 0:A=1
46 1:B=2
47 2:C=3
48 #endif
49