Last active
April 24, 2019 11:38
-
-
Save gitmarek/5e102bb548aba8bce6bfd1043c1517fe to your computer and use it in GitHub Desktop.
Simple lists in C
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> | |
typedef struct elem { | |
void *data; | |
struct elem *next; | |
} elem_t; | |
int main(int argc, char **argv) { | |
char *line; | |
size_t n; | |
elem_t *e, *l; | |
// allocate list l | |
l = (elem_t*) malloc(sizeof(elem_t)); | |
// and its metadata | |
l->data = malloc(sizeof(int)); | |
// read all lines from STDIN | |
for (e=l; getline(&line, &n, stdin) != -1; e = e->next) { | |
// append line to l | |
e->next = (elem_t*) malloc(sizeof(elem_t)); | |
e->next->data = line; | |
// make getline allocate resources for another round | |
line=NULL; | |
n=0; | |
} | |
// this is how you traverse l | |
for (e=l; e=e->next; ) printf("%s", (char*) e->data); | |
// e.g. | |
for (e=l, n=0; e=e->next; n++); | |
printf("No. of lines read: %ld\n", n); | |
// free l and its elements | |
while (l) { | |
e = l->next; | |
free(l->data); | |
free(l); | |
l = e; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment