dynamically allocating array of struct

David Geary dmg at ssc-vax.UUCP
Sat Apr 8 03:02:42 AEST 1989


In article <3658 at uhccux.uhcc.hawaii.edu>, (Cs411s03) writes: 

|| 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 <stdio.h>
|| #include <malloc.h>

|| #define NUMRECS 60

|| struct ttst {
|| 	int num;
|| };
|| 
|| struct ttst (*tptr)[];

  No - what you want here is:		struct ttst	*tptr;

  You simply need a pointer to struct ttst.  
  Below we will allocate an array of struct ttst's, and tptr will point to the first
  struct in the array.

|| 
|| main()
|| {
|| 	int i, j;
|| 
|| 	if ((tptr = (struct ttst (*)[]) \
|| 	malloc(sizeof(struct ttst) * NUMRECS)) == (struct ttst (*)[]) 0) {
|| 		perror("malloc");
|| 		exit(1);
|| 	}

Should be:  if( (tptr = (struct ttst *)malloc(sizeof(struct ttst) * NUMRECS)) == NULL) {
	      perror("malloc");
	      exit(1);
	    }

(BTW the '\' character in your code above should not be accepted by the compiler.  This is
used to extend lines for the preprocessor, not the compiler)

So now we have:

--------                      ________________________
| tptr |--------------------->|                       |
--------                      |  struct   ttst        |
			      -------------------------
                              |                       |
                              |  struct   ttst        |
                              -------------------------
                              |                       |
                              |  struct   ttst        |
                              -------------------------
					  .
					  .
					  .
 
|| 	printf("sizeof = %d\n", sizeof(struct ttst) * NUMRECS);
|| 

  From here on down, all tptr[i]->num should be tptr[i].num

  Realize that tptr[0], tptr[1], tptr[2], etc. are all struct ttst's, NOT pointers
  to struct ttst's.  Therefore, we have tptr[i].num, NOT tptr[i]->num.

|| 	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);
|| }
|| 

  
-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ David Geary, Boeing Aerospace, Seattle                 ~ 
~ "I wish I lived where it *only* rains 364 days a year" ~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



More information about the Comp.lang.c mailing list