public

  • Download Gist
Passing a pointer to a function in C.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
struct Person {
char name[16];
char text[24];
};
 
struct Node {
void* data;
struct Node* next;
};
 
struct List {
struct Node* head;
};
 
struct Person* person_new(char* name, char* text)
{
struct Person* p = (struct Person*) malloc(sizeof(struct Person));
strncpy(p->name, name, 15);
p->name[15] = '\0';
strncpy(p->text, text, 23);
p->name[23] = '\0';
return p;
}
 
struct Node* node_new(void* data)
{
struct Node* n = (struct Node*) malloc(sizeof(struct Node));
n->data = data;
n->next = NULL;
return n;
}
 
struct List* list_append(struct List* lis, void* data)
{
struct Node* new_node = node_new(data);
struct Node* n = lis->head;
if (! n) {
lis->head = new_node;
} else {
while (n->next) {
n = n->next;
}
n->next = new_node;
}
return lis;
}
 
void traverse(struct List* a, void (*f)(void*))
{
struct Node* n = a->head;
while (n) {
f(n->data);
n = n->next;
}
}
 
static void print(void* data) {
struct Person* p = (struct Person*) data;
printf("%s\n", p->name);
}
 
int main(int argc, char** argv)
{
/* create a sample two-item list and test it */
struct List ps;
struct Person* p;
struct Person* p2;
 
p = person_new("Jack", "");
list_append(&ps, p);
p2 = person_new("Jill", "");
list_append(&ps, p2);
 
traverse(&ps, &print);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.