Created
June 11, 2021 19:20
-
-
Save izabera/20fa0b7d6de5e5c224c0895b0b90e508 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
char **func_that_returns_strings(int nstrings) { | |
// first dump all the strings into a contiguous buffer, separated by \0 | |
char buf[100]; | |
size_t size = 0; | |
for (int i = 0; i < nstrings; i++) | |
size += sprintf(buf + size, "qqq%dzzz", i) + 1; | |
// then allocate a buffer for the pointers, with extra space at the end | |
char **strings = malloc(sizeof *strings * (nstrings + 1) + size); | |
char *newbuf = (char *)(strings + (nstrings + 1)); | |
memcpy(newbuf, buf, size); | |
char **s = strings; | |
*s = newbuf; | |
for (char *p = newbuf; p < newbuf + size; p++) | |
if (!*p) | |
*++s = p+1; | |
*s = NULL; | |
return strings; | |
} | |
int main() { | |
char **strings = func_that_returns_strings(5); | |
for (char **s = strings; *s; s++) | |
puts(*s); | |
// everything gets freed in a single call | |
free(strings); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment