Article View: comp.lang.c.moderated
Article #2378Re: Newbie Question: Multiple indirection
From: Brian V. McGroarty
Date: Sun, 24 Mar 1996 17:48
Date: Sun, 24 Mar 1996 17:48
59 lines
2088 bytes
2088 bytes
Terry Heath wrote:
>I have seen many references in text I have read about multiple
>indirection (i.e. **p); I seen how to initilize them and so on. The
>question is:
> Why would it be necessary to use such a pointer, and when?
Consider a case where you need to create a 2 dimensional array whose size
in each of the 2 dimensions is not known at compile time. Examples are
matrix math functions or arrays of strings.
With double indirection, you can make "anytype **mainPointer" a pointer to
an array of pointers to rows of data, fill each of the pointers to rows of
data with a pointer to a row of data and access the data with bracket
operators as though it were a standard array.
Example:
char **forceField;
void DoLittle( void )
{
AnyFunction( 10, 20 );
}
void AnyFunction( int rows, int columns )
{
int allocLoop;
forceField= (char **)malloc( sizeof( char * ) * rows );
/* insert check to see you got !NULL, deal with failures */
for( allocLoop= 0; allocLoop< rows; allocLoop++ )
{
forceField[ allocLoop ]= (char *)malloc( sizeof( char ) * columns );
/* insert check to see you got !NULL, deal with failures */
}
/* now you can do the following */
forceField[ 5 ][ 6 ]= 1;
forceField[ 0 ][ 0 ]++;
/* clean up */
for( allocLoop= 0; allocLoop< rows; allocLoop++ )
{
free( forceField[ allocLoop ] );
}
free( forceField );
}
---
Brian Valters McGroarty -- brianmcg@bix.com
phone/fax (847) 439-7714
Technical Details
Message-ID:
<4j41tt$nt3@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4j06lv$7ve@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail From: brianmcg@interaccess.com (Brian V. McGroarty) Newsgroups: comp.lang.c.moderated Subject: Re: Newbie Question: Multiple indirection Date: 24 Mar 1996 11:48:45 -0600 Organization: Internet Squire Sender: clc@solutions.solon.com Approved: clc@solutions.solon.com Message-ID: <4j41tt$nt3@solutions.solon.com> References: <4j06lv$7ve@solutions.solon.com> Reply-To: brianmcg@interaccess.com NNTP-Posting-Host: solutions.solon.com X-Newsreader: Internet Squire 1.20