how has C bitten you?

Guy Harris guy at sun.uucp
Sat Aug 31 14:36:43 AEST 1985


> Not really a bite, but I remember when I was first learning C
> I was quite bewildered by the fact that you couldn't really
> declare your own 'argv', that is, you couldn't declare an
> array of pointers to fixed length buffers except perhaps by:
> 
> char *myargv[] = {
> 	"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",
> 	"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",
> 
> 	etc
> 
> I mean, argv seemed kinda holy to me, disturbing.

If you want an array of pointers to fixed-length buffers, you can declare it
as long as the number of such pointers can be determined at the time you
write the code.

	char bufs[3][20];

	char *bufps[3] = {
		bufs[0],
		bufs[1],
		bufs[2],
	};

If the number can't be fixed when you write the code, you can set up "bufps"
at run time.

Also note that "argv" isn't a pointer to an array of pointers to fixed-length
buffers, it's a pointer to an array of pointers to strings, which you *can*
declare.

> P.S. I know argv is var length, but that would be even harder to declare!

The secret is that "argv" (or, more correctly, what "argv" points to)
*isn't* declared.  Pointers need not point to things which have been
declared; "malloc" returns pointers to objects fabricated on the fly.  If
you have "n" arguments ("n" is a variable here), just do

	register char **argv;

	argv = (char **)malloc(n * sizeof(char *));

And you can fill them in.

	Guy Harris



More information about the Comp.lang.c mailing list