Skip to content

Instantly share code, notes, and snippets.

@boxofrad
Created September 14, 2013 21:44
Show Gist options
  • Save boxofrad/6565932 to your computer and use it in GitHub Desktop.
Save boxofrad/6565932 to your computer and use it in GitHub Desktop.
Function that "returns" an array of structs
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct Thing { char *name; };
void get_things(int *number_of_things, struct Thing **things)
{
int num = 10;
struct Thing *tmp = malloc(sizeof(struct Thing) * num);
for (int i = 0; i < num; i++) {
tmp[i].name = malloc(sizeof(char) * 8);
sprintf(tmp[i].name, "Hello #%d", i);
}
*things = tmp;
*number_of_things = num;
}
int main(int argc, const char *argv[])
{
struct Thing *things;
int number_of_things;
get_things(&number_of_things, &things);
for (int i = 0; i < number_of_things; i++) {
printf("%s\n", things[i].name);
free(things[i].name);
}
free(things);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment