Skip to content

Instantly share code, notes, and snippets.

@izabera
Created June 11, 2021 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izabera/20fa0b7d6de5e5c224c0895b0b90e508 to your computer and use it in GitHub Desktop.
Save izabera/20fa0b7d6de5e5c224c0895b0b90e508 to your computer and use it in GitHub Desktop.
#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