Casting for a fish that never arrived

Don E. Davis ded at aplvax.UUCP
Tue May 14 04:46:14 AEST 1985


Here is a problem which cropped up recently.  I had two two dimensional
arrays of pointers to character strings (as represented by Cwords and Pwords
below).  I wanted to point to either Cwords or Pwords
and be able to flip back and forth between two lists of strings
by indexing.  For example, if Words pointed to Cwords, then Words[0][0] would
point to "hello" and Words[1][0] would point to "goodbye".  If Words pointed
to Pwords the two choices would be "foo" and "foobar".  The only problem is,
I had a hard time getting this to work.  What I needed was something to put in
the place of CASTING EXPRESSION below.  Apparently there is no way to
perform this kind of cast (the array's second dimension is the problem). 

Of course, I could have used pointer arithmetic 
(e.g., printf("%s\n",*(Words+i*4+j)), but wound up using a typedef instead
since the WORD[][] format made my code a lot cleaner.

What do you say, gang, is there some CASTING EXPRESSION I could have used?

/*-----------------------------------------------------------------------*/

char *Cwords[2][4] = {
	{"hello","go","here","see"},
	{"goodbye","come","there","hear"} 
};
char *Pwords[2][4] = {
	{"foo","foo","foo","foo"},
	{"foobar","foobar","foobar","foobar"} 
};
char *Words;

main()
{
	int i,j;

	Words = (char *)Cwords;
	for (i=0; i<2; i++)
		for (j=0; j<2; j++)
			printf("%s\n",(CASTING EXPRESSION)Words[i][j]);
	Words = (char *)Pwords;
	for (i=0; i<2; i++)
		for (j=0; j<2; j++)
			printf("%s\n",(CASTING EXPRESSION)Words[i][j]);
}

/*-------------------------------------------------------------------------*/

Here is a solution which works.  I find it hard to believe this
can't be done without a typedef (or explicit pointer arithmetic), but
haven't been able to find a way yet.

typedef char *SYNTAX[4];
SYNTAX Cwords[2] = {
	{"hello","bye","go","come"},
	{"say","can","you","see"} 
};
SYNTAX Pwords[2] = {
	{"foo","foo","foo","foo"},
	{"foo","foo","foo","foo"} 
};
SYNTAX *Words;

main()
{
	int i,j;

	Words = (SYNTAX *)Cwords;
	for (i=0; i<2; i++)
		for (j=0; j<2; j++)
			printf("%s\n",Words[i][j]);
	Words = (SYNTAX *)Pwords;
	for (i=0; i<2; i++)
		for (j=0; j<2; j++)
			printf("%s\n",Words[i][j]);
}
-- 

					Don Davis
					JHU/APL
				...decvax!harpo!seismo!umcp-cs!aplvax!ded
				...rlgvax!cvl!umcp-cs!aplvax!ded



More information about the Comp.lang.c mailing list