struct {int **i}; problem
Roy Johnson
rjohnson at shell.com
Wed Mar 27 06:25:20 AEST 1991
In article <1991Mar23.213414.12572 at cs.widener.edu> sven at cs.widener.edu (Sven Heinicke) writes:
> struct imatrix {
> char **board;
> int size;
> };
> typedef struct imatrix iMATRIX;
> main()
> {
> int l;
> iMATRIX playing;
> .
> .
> .
> playing.board = (int**)malloc(sizeof(int *) * playing.size * playing.size);
I think what you want here is
playing.board = (int **)malloc(sizeof(int *) * playing.size);
which gives you one dimension of the board. Then to get the other dimension
you do
> for(l = 0;l < playing.size * playing.size;l++)
> *(playing.board) = (int*)malloc(sizeof(int));
which I gather is to allocate the other dimension of the board. What
you are doing here is malloc-ing space, assigning the pointer, and
then losing the pointer when you reassign the same thing again. This
loop should be like:
for (l = 0; l < playing.size; l++)
playing.board[l] = (int *)malloc(sizeof(int) * playing.size);
playing.board is then an array of arrays% of ints. However, note that
you declared playing.board to be pointer to pointer to char. You will
need to determine which you really want.
> reset(matrix)
iMATRIX *matrix;
> {
> int x,y;
> for(x = 0;x < matrix->size;x++)
> for(y = 0;y < matrix->size;y++)
> (*(matrix->board+x)+y) = x * matrix->size + y + 1;
> }
For clarity, I recommend the (arguably slower)
matrix->board[x][y] = x * matrix->size + y + 1;
which should do the same thing. Should means I haven't tried it. 8^)
If you want to keep your pointer-dereference notation, you want:
*(*(matrix->board+x)+y) = x * matrix->size + y + 1;
that is, one more level of indirection.
Hope this helps. Hope it's all right.
% I'm using the terms array and pointers rather freely, which I'm sure
will inspire much "clarification". Conceptually, array of arrays is
what you have.
--
======= !{sun,psuvax1,bcm,rice,decwrl,cs.utexas.edu}!shell!rjohnson =======
Feel free to correct me, but don't preface your correction with "BZZT!"
Roy Johnson, Shell Development Company
More information about the Comp.lang.c
mailing list