Malloc and arrays...

Dave P. Schaumann dave at cs.arizona.edu
Mon Mar 4 04:12:12 AEST 1991


In article <1991Mar3.172942.3116 at nntp-server.caltech.edu> eychaner at suncub.bbso.caltech.edu writes:
>Warm up those flame guns!  It's time for Another Novice Question!
>
>I know this is partly covered in the FAQ, but it didn't seem to have quite
>the answer I want.
>[...]
>  bigmemory = (char *) malloc (OODLES_O_BYTES);
>I can access the chunk of memory as though it were an array, like so:
>  bigmemory [RIGHT_HERE] = SOME_CHARACTER;
>[becomes]
>  *(bigmemory + RIGHT_HERE) = SOME_CHARACTER;

Right.

>  bigmemory [RIGHT_HERE][RIGHT_NOW] = SOME_CHARACTER;

/* This requires that OODLES_O_BYTES is divisible by NUMBER_OF_ENTRIES_WANTED.
*/
char **two_d = malloc(NUMBER_OF_ENTRIES_WANTED * sizeof(char *))

  for( i = 0 ; i < NUMBER_OF_ENTRIES_WANTED ; i++ )
    two_d[i] = &bigmemory[ i * OODLES_O_BYTES / NUMBER_OF_ENTRIES_WANTED ]

Now you can say two_d[RIGHT_HERE][RIGHT_NOW] = SOME_CHARACTER
Provided I haven't made an Incredibly Stupid Mistake (TM), you should be
able to modify this to your needs.

-- 
		Dave Schaumann		dave at cs.arizona.edu
'Dog Gang'!  Where do they get off calling us the 'Dog Gang'?  I'm beginning to
think the party's over.  I'm beginning to think maybe we don't need a dog.  Or
maybe we need a *new* dog.  Or maybe we need a *cat*! - Amazing Stories



More information about the Comp.lang.c mailing list