dynamically allocating array of struct

Cs411s03 cs411s03 at uhccux.uhcc.hawaii.edu
Wed Apr 5 18:36:06 AEST 1989


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)[];

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



More information about the Comp.lang.c mailing list