Mail Archives: djgpp/2001/01/12/13:21:37
[This is a basic C question, and thus had better been asked in
comp.lang.c or de.comp.lang.c]
Waldemar Schultz <schultz AT ma DOT tum DOT de> wrote:
> int poly(int n, int data[][2]);
> void do_poly(int n)
> {
> int **data=malloc(... n);
> poly(n, data); //call the function
> }
> and of course GCC warns me about the parameter type mismatch.
Arrays-of-arrays are one of the cases where the fundamental
incorrectness of the often-heard statement that "arrays are the same
as pointers to their first elements" shows through. The above code
snippet is faulty, and the GCC warning is very well justified.
You should have done this, instead:
int (*data)[2] = malloc(n * sizeof (*data))
'data' is a pointer to an array of 2 ints now, not a pointer to
pointer to int. This type is compatible to the argument of poly(),
yours isn't.
The underlying problem is that the storage described by an int [n][2]
is guaranteed by the C language to be in a single, contiguous block of
exactly 2*n*sizeof(int) bytes, whereas the storage behind an int **
can be fragmented into n separate hunks, with no way of telling how
large each of them is.
Another error in what you showed of your code: you only allocate
memory to hold the pointers-to-pointer-to-int themselves, but not the
pointers-to-int they are supposed to point to.
--
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.
- Raw text -