Created
May 24, 2018 15:54
-
-
Save nbassler/13e3d970ab2bf0357890dbecbf9f743e to your computer and use it in GitHub Desktop.
Working with list of pointer to structures in C.
This file contains hidden or 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> | |
/* gcc test_ppstruct.c -o test_ppstruct -Wall */ | |
struct point { | |
double x; | |
double y; | |
}; | |
/* this is OK */ | |
int point_init(struct point **pt, int i) { | |
i++; | |
*pt = malloc(sizeof(struct point)); | |
(*pt)->x = 10.0 * i; | |
(*pt)->y = 11.0 * i; | |
return 1; | |
} | |
/* this is OK */ | |
int point_init2(struct point **pt, int i) { | |
struct point *p; /* easier to read code by avoiding long pointer names */ | |
i++; | |
p = malloc(sizeof(struct point)); /* now points to good place in mem */ | |
p->x = 10.0 * i; | |
p->y = 11.0 * i; | |
*pt = p; /* copy the address of p to *pt. p should go out of scope then */ | |
return 1; | |
} | |
int main(int argc, char *argv[]) { | |
struct point **points; | |
size_t npoints = 2; | |
size_t i = 0; | |
points = malloc(npoints * sizeof(*points)); | |
for (i = 0; i < npoints; i++) { | |
// point_init(&points[i], (int) i); | |
point_init2(&points[i], (int) i); | |
printf("%li %f %f\n", i, points[i]->x, points[i]->y); | |
} | |
/* now free it properly */ | |
for (i = 0; i < npoints; i++) { | |
free(points[i]); | |
} | |
free(points); | |
/* valgrind happy */ | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment