callocing 2D array

ANDREW BRUSH smbrush at lims05.lerc.nasa.gov
Tue Apr 30 22:05:20 AEST 1991


In article <122085 at unix.cis.pitt.edu>, ich at unix.cis.pitt.edu (Il-hyung  Cho) writes...
>Hello, guys.
>I'm not quite good at C, but I hope some of you could help my problem.
>I'm trying to implement 2D array whose size is not known until run time.
>The way I tried was like follows:
> 
>---------------------------------------------------------------
>typedef int **ary;
>main()
>{
>	int **i;
> 
>	i = (ary) calloc(25, sizeof(int));
        ^
        Now *i or i[0] has a value ... but is all zero's.

>	i[0[0] = 1;	/* Segmentation falut */
            ^
            You are trying to assign a value to a memory location 
            whose address is probably garbage (all zeros).
>}
> 
>------------------------------------------------------------------
>As indicated, the array cannot be assigned any value.
>How do I solve the problem?
> 
>I'll really appreciate any of your help.
>Thanks.
>
Try this:

int nrows=5;
int ncols=5;
int **array;
int ii;

	array = (int **)calloc(nrows, sizeof(int*));
	/* should check for successful calloc here */
	for (ii=0; ii<=ncols-1; i++){
		array[ii] = (int *)calloc(ncols, sizeof(int));
		/* check calloc success */
		}
Now, array is a pointer to nrows pointers to ncols int's.  That is, 
array[1] is a pointer to the start of the second row.  You can nest 
more loops in there to get more dimensions.  Make sure you check to 
see if *ALL* the calloc's worked, or you will eventually be assigning 
a value to NULL, which looks like what your program always does.

This is probably in the FAQ, but I didn't look, either.

For a very good discussion of large dynamic arrays, try to find the 
Oct, 1988 Personal Engineering and Instrumentation News, pp63-71.
	
Andrew S. Brush             | SMBRUSH at EARTH.lerc.nasa.gov
Sverdrup Technology         | 2001 Aerospace Parkway
NASA LeRC Group             | Brook Park, OH 44142
"Opinions are Mine, Only"   | (216) 826-6770



More information about the Comp.lang.c mailing list