Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!swrinde!cs.utexas.edu!asuvax!noao!ncar!gatech!usenet.ins.cwru.edu!eagle!lims05.lerc.nasa.gov!smbrush From: smbrush@lims05.lerc.nasa.gov (ANDREW BRUSH) Newsgroups: comp.lang.c Subject: Re: callocing 2D array Message-ID: <1991Apr30.122658.7459@eagle.lerc.nasa.gov> Date: 30 Apr 91 12:05:20 GMT References: <122085@unix.cis.pitt.edu> Sender: news@eagle.lerc.nasa.gov Reply-To: smbrush@lims05.lerc.nasa.gov Distribution: usa Organization: NASA Lewis Research Center Lines: 57 News-Software: VAX/VMS VNEWS 1.3-4 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