realloc questions

Shiping Zhang ping at cubmol.bio.columbia.edu
Wed Feb 28 08:51:22 AEST 1990


In article <4563 at rouge.usl.edu> pcb at 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;j<A->row;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;j<A->new_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



More information about the Comp.lang.c mailing list