realloc questions
William P. Kaufman
wkaufman at oracle.oracle.com
Fri Mar 2 09:47:59 AEST 1990
Just one more thing to add to the discussion,...
To remind you (I added the previous corrections someone suggested to the code):
In article <4563 at rouge.usl.edu> pcb at gator.cacs.usl.edu (Peter C. Bahrs) writes:
>
> typedef struct a
> { int row, col; long **arr} A;
> A *temp;
>
> temp=(A *) calloc (1, sizeof(A)); /* then initialize row and col ... */
> temp->arr=(long *)calloc (temp->row, sizeof(long *));
> for (j=0;j<temp->row;j++)
> temp->arr[j] = calloc(col,sizeof(long));
>
>1) I should now be able to index as temp->arr[j][k], correct?
>2) or should type A contain long *arr[] instead?
That would be fine as long as you know the number of rows
ahead of time, as in "long *arr[30]", or some such. Otherwise, "type
var[]" is only good if the variable is actually declared somewhere
else--say in an extern definition, or as a function parameter. The
compiler needs to know at compilation time how large the objects are.
As it is, it's just fine.
>Now I want to redimension the type to a new_row and new_col.
>
> temp->arr=(long *) realloc ((char *)&temp->arr, new_row*sizeof(long *));
> for (j=0;j<temp->new_row;j++)
> temp->arr[j] = realloc(new_col,sizeof(long));
AUUGGGHHH!! Sorry, I just recently had to re-write someone's
code that did this sort of thing. You're re-allocating temp->arr
before you re-allocate temp->arr[j]! Just switch the order of the
realloc() calls and you should be fine.
Happy hunting!
-Bill Kaufman
Nowhere you can get to by e-mail
More information about the Comp.lang.c
mailing list