Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!columbia!cubmol!ping From: ping@cubmol.bio.columbia.edu (Shiping Zhang) Newsgroups: comp.lang.c Subject: Re: realloc questions Message-ID: <1990Feb27.215122.10441@cubmol.bio.columbia.edu> Date: 27 Feb 90 21:51:22 GMT References: <4563@rouge.usl.edu> Reply-To: ping@cubmol.bio.columbia.edu (Shiping Zhang) Distribution: usa Organization: Dept. of Biology, Columbia Univ., New York, NY Lines: 49 In article <4563@rouge.usl.edu> pcb@gator.cacs.usl.edu (Peter C. Bahrs) writes: >This may be a naive discussion but here goes... > >I want to create an N (2 for now) dimensional datum of long integers. > > typedef struct a > { int row, col; long **arr} A; > A *temp; Why don't you declare temp as varible A instead of a point to A, and omit the following line of code to allocate space for temp? > temp=(A *) calloc (1, sizeof(A)); /* then initialize row and col ... */ > A->arr=(long *)calloc (A->row, sizeof(long *)); ^ ^^^^^^ ^ A (and also in following lines) should be temp and the cast should be (long **). > for (j=0;jrow;j++) > A->arr[j] = calloc(col,sizeof(long)); ^ Need cast (long *). >1) I should now be able to index as A->arr[j][k], correct? Yes, with the corrections. >2) or should type A contain long *arr[] instead? No. "long *arr[]" is illegal code in C. >Now I want to redimension the type to a new_row and new_col. > > A->arr=(long *) realloc ((char *)&A->arr, new_row*sizeof(long *)); ^ ^ The cast should (long **) and the address operator should NOT be used. > for (j=0;jnew_row;j++) > A->arr[j] = realloc(new_col,sizeof(long)); ^ ^ Need cast. >3) This doesn't work (sometimes). I understand realloc will retain values Not surprising. With the corrections, it should work all the time. -ping