help needed about dynamic space allocation
Alastair Adamson
alastair at axis.UUCP
Sun Nov 23 21:36:14 AEST 1986
In article <1046 at lifia.UUCP> fano at lifia.UUCP (Rampa*) writes:
>
> float **sig; /* matrix declaration */
> ....
> sig = (int *)malloc(n * sizeof(int)); /* allocates space for sig */
>
>during the compiling time, I get the following warning:
> "combin1.c", line 220: warning: illegal pointer combination
Try changing the initialisation of sig to
sig = (float **)malloc(n * sizeof(float *));
and the warning message will go away. Since sig is a double pointer to
a float, that is what you want malloc to return. You are creating a dope
vector, where each element of the vector is in fact a pointer a row
which in turn is a pointer to the elements of that row; thus:
--- -----------
| |------------>| |
| |----- -----------
--- |
| -----------
------->| |
-----------
The technique is common. Each element of the 2-dimensional table is float.
Thus the pointer to each row is a (float *). Sig points to these row pointers
ans is thus is (float **).
By the way, another solution which uses less memory is simplt to
get hold of enough space for all the elements of the table and do
the addressing yourself. For example a N x M table can be dealt with:
table = (type *)malloc(N * M * sizeof(type));
...
table[i * N + j] = value; /* put value in table[i][j] */
...
free((char *)table); /* free the space */
Alternatively, to make acceses *look* better, use
#define Table(i, j) table[i * N + j]
and
Table(i, j) = value;
Bonne chance,
Alastair
More information about the Comp.lang.c
mailing list