ich@unix.cis.pitt.edu (Il-hyung Cho) (04/30/91)
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));
i[0[0] = 1; /* Segmentation falut */
}
------------------------------------------------------------------
As indicated, the array cannot be assigned any value.
How do I solve the problem?
I'll really appreciate any of your help.
Thanks.
PS> If you are willing to help me, please email me.
Thanks a bunch.
smbrush@lims05.lerc.nasa.gov (ANDREW BRUSH) (04/30/91)
In article <122085@unix.cis.pitt.edu>, ich@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@EARTH.lerc.nasa.gov Sverdrup Technology | 2001 Aerospace Parkway NASA LeRC Group | Brook Park, OH 44142 "Opinions are Mine, Only" | (216) 826-6770