Need help with array of pointers to structure

Guy Greenwald ggg at sunquest.UUCP
Mon Jul 10 05:07:06 AEST 1989


In article <8587 at attctc.DALLAS.TX.US>, bobc at attctc.DALLAS.TX.US (Bob Calbridge) writes:
> I could sure use a hand (or some talented fingers.)  Here is the situation.
> I have a structure defined which includes some pointers, counters and 
> a buffer.
> I also have an array of pointers to twelve of these structures.  As an 
> example, if I want to clear each of the buffers and set a pointer to the 
> beginning of the
> buffer plus set a counter to zero, I need to know how to address and 
> manipulate the elements of the structure.  I thought I understood the 
> mechanism but I keep getting error messages from the compiler.  Here is
> basically what I thought was proper.  vtable is define as
> 
> struct *vtable [] = {&v1, &v2, &v3,......v12};

Well, vtable is defined wrong. If the struct is declared to be "struct
mystruct", then vtable should be "struct mystruct *vtable[]", etc.

> 
> I was trying to do something like this:
> 
> for (i=0; i < 12; i++) { 
>    vtable[i]->ptr = vtable[i]->buf;
>     for (j=0; j<80; j++)
> 	vtable[i]->*ptr = -1;
> }
> 
> where the intent is to place -1 into the 80 positions of the buffer and to do
> this for each of the 12 structures.  
> 
> Can anyone tell me what I'm doing wrong or if there is a better way.  Even if
> there is a better way, I'd like to know what my misunderstanding is here.

Yes, there is a better way. Try using a table of structures rather than
naming each structure "v1", "v2", ..., "v12". The names you are using suggest
an array. Here is one way to do it:


#define BUFSIZE	80
#define NUM	12

struct mystruct {
	char buf[BUFSIZE];
	char *ptr;
	int cnt;
} vtable[NUM];

main()
{
	int i, j;
	struct mystruct *vptr;

	for (i = 0; i < NUM; i++) {
		vptr = &vtable[i];
		vptr->ptr = vptr->buf;
		for (j = 0; j < BUFSIZE; j++)
			vptr->buf[j] = -1;
		vptr->cnt = 0;
	}
}

Note the definition of vptr above; this is how to declare a pointer to a 
structure. The code shows how to use it to avoid the awkward appearance of
"vtable[i].member".

Consider whether you really need to fill the buffer with negative ones. I
don't know your application, but this kind of thing is rarely necessary.

Hope this helps.

--G. Guy Greenwald II



More information about the Comp.lang.c mailing list