[comp.lang.c] Novice question on vectors of pointers

jjr@rushpc (John J. Rushford Jr) (04/29/91)

I hope this question is not too OS specific.  Point me elsewhere if it is.

How does one use a vector of pointers to member names.  I'm specifically
trying to use getgrnam(3C) in UNIX SVR3.2 and I want to print to 'stdout'
all the entries in **gr_mem.  Below is an example of what I'm trying to
work with.  I don't have any problem with the remaining elements in the
structure.  It's **gr_mem I don't understand.  How do you work with it?

EXAMPLE:

#include <stdio.h>
	
/* From '/usr/include/grp.h'
struct group {
	char *gr_name;    /* the name of the group */
	char *gr_passwd;  /* the encrypted group password */
	int  gr_gid;      /* the numerical group ID */
	char **gr_mem;    /* vector of pointer to member names */
	};

struct group *pntr, *getgrnam();

main()
{
	pntr = getgrnam("other");

	fprintf(stdout, "%s\n", pntr->gr_name);
	fprintf(stdout, "%s\n", pntr->gr_passwd);
	fprintf(stdout, "%d\n", pntr->gr_gid);
	

	return 0;
}


thanks a ton.
-- 

John
----
Westminster Colorado	

john@newave.UUCP (John A. Weeks III) (04/30/91)

In article <1991Apr29.051313.2064@rushpc> jjr@rushpc (John J. Rushford Jr) writes:
>I hope this question is not too OS specific.  Point me elsewhere if it is.

Not at all.

> How does one use a vector of pointers to member names.

Fun with arrows and dots!

> It's **gr_mem I don't understand.  How do you work with it?
> struct group {
>	char *gr_name;    /* the name of the group */
>	char *gr_passwd;  /* the encrypted group password */
>	int  gr_gid;      /* the numerical group ID */
>	char **gr_mem;    /* vector of pointer to member names */
>	};

OK. gr_mem is a pointer to a pointer to a character.  The second pointer
is probably a string, so you have:

In pntr structure:
	gr_name ----> null terminated string
	gr_passwd ----> null terminated string
	gr_gid  <- an integer location
	gr_mem ----> some_location ----> null terminated string

The reason you use this "some_location" hop is that some_location can
an array (a.k.a. vector).  For example:

	gr_mem ----> some_location[ 0 ] ----> null terminated string
		     some_location[ 1 ] ----> null terminated string
		     some_location[ 2 ] ----> null terminated string
		     some_location[ 3 ] ----> null terminated string
		     ...

So, if you want to print out the third string, use the following:

	printf( "%s\n", pntr->gr_passwd[ 2 ] );

To allocate one of these puppies, allocate the vector first, then
step through each element of the vector and allocate the strings.
When you free this, free the strings first, then free the vector.
If you free the vector first, you will loose the addresses of the
strings.

-john-

-- 
=============================================================================
John A. Weeks III               (612) 942-6969             john@newave.mn.org
NeWave Communications                       ...uunet!tcnet!wd0gol!newave!john