Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!pasteur!helios.ee.lbl.gov!nosc!humu!uhccux!cs411s03 From: cs411s03@uhccux.uhcc.hawaii.edu (Cs411s03) Newsgroups: comp.lang.c Subject: dynamically allocating array of struct Keywords: dynamic array struct Message-ID: <3658@uhccux.uhcc.hawaii.edu> Date: 5 Apr 89 08:36:06 GMT Distribution: usa Organization: University of Hawaii Lines: 55 I am having difficulty writing a program which dynamically allocates an array of structs via malloc() and casting. The program seems to compile OK, but at run time I am addressing the SAME struct over and over, I want to step thru them with an index. The program goes like so: /* malloc struct test */ #include #include #define NUMRECS 60 struct ttst { int num; }; struct ttst (*tptr)[]; main() { int i, j; if ((tptr = (struct ttst (*)[]) \ malloc(sizeof(struct ttst) * NUMRECS)) == (struct ttst (*)[]) 0) { perror("malloc"); exit(1); } printf("sizeof = %d\n", sizeof(struct ttst) * NUMRECS); for (i = j = 0; i < NUMRECS; i++) { tptr[i]->num = ++j; printf("Rec: %x %d %d\n", tptr[i], i, tptr[i]->num); } printf("---------------\n"); for (i = 0; i < NUMRECS; i++) printf("Rec: %x %d %d\n", tptr[i], i, tptr[i]->num); free(tptr); exit(0); } The program will do much more than this once completed, this program was just to test the basic concept of dynamically allocating the structures rather than just declaring a fixed length array ... The first loop looks as if it is working, but the second loop proves it is not. It seems that the same structure is being written to over and over. I must be missing something fundamental here ... cs411s03!uhccux