** help...
Rhodri James
rmj at tcom.stc.co.uk
Wed Aug 22 00:35:33 AEST 1990
In article <2409 at dsacg2.dsac.dla.mil> nol2321 at dsacg2.dsac.dla.mil (Jim Dunn) writes:
>Why can't I do the following?!? (C'mon you gurus...)
>
>typedef struct _window {
> int x;
> int y;
> int **array;
[etc]
>} WINDOW;
>
>main()
>{
> int x, xL = 10;
> WINDOW *w1;
>
> w1 = (WINDOW *) malloc(sizeof(WINDOW));
>
>/* the problem is next */
> w1->array = malloc( xL * sizeof(int) );
You want the whole list or just the short version? :-)
1) array is an int ** so the malloc should be cast to that
2) the "elements" are int *, so that should be what you take sizeof.
Pointers haven't been equivalent to ints for some while.
3) this isn't vastly relevant to PC applications, but doing a
multiplication as your argument to malloc is just asking for alignment
trouble. Either calloc(xL, sizeof(int *)), or (more grungily)
malloc(sizeof(int *[xL])) (will this work if xL is a variable?)
4) you really ought to consider #defining xL rather than making it a
variable. Unless you have pressing reasons otherwise.
>/* isn't the above line legal, or how can I allocate mem for the storage */
It's legal, but hardly sensible. Actually, it isn't all that legal.
> for(x=0;x < xL; x++)
> w1->array[x] = (int *) malloc( 10 * sizeof(int *) );
This time you should be taking the sizeof an int! Comments above about
multiplicative mallocs apply, and this time malloc( sizeof(int[10]))
does work (I think).
>}
>
>Jim
>jdunn at dsac.dla.mil
Hope this helps.
Rhodri
--
* Windsinger * "Nothing is forgotten..."
* rmj at islay.tcom.stc.co.uk * Mike Whitaker
* or (occasionally) * "...except sometimes the words"
* rmj10 at phx.cam.ac.uk * Phil Allcock
More information about the Comp.lang.c
mailing list