Created
September 14, 2013 21:44
-
-
Save boxofrad/6565932 to your computer and use it in GitHub Desktop.
Function that "returns" an array of structs
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 <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