A pointer to a 3-D array, or an array of ptrs to 2-D arrays?

Conor P. Cahill cpcahil at virtech.uucp
Thu Nov 16 01:53:02 AEST 1989


In article <2765 at levels.sait.edu.au>, MARWK at levels.sait.edu.au writes:
> Why does (1) work but (2) does not?
> 
> (1) p = (int (*) [13][2][64]) malloc (sizeof(int) * 13 * 2 * 64)
>     
>     *p[i][j][k] = 6
> 
> (2) p = (int (*) [2][64]) malloc (sizeof(int) * 13 * 2 * 64)
> 
>     p[i][j][k] = 6

This stuff depends upon how you declare p not really on how you cast
the return from malloc().

if p is declared as

	int  (*p) [13][2][64];

then p is a pointer to an array[13][2][4] of ints.  Therefore to 
place a value into position i,j,k you need to:

	(*p)[i][j][k] = 6;

which says place a 6 into element i,j,k of the array to wich p points.

	p[i][j][k] = 6;

says place a 6 into the i,j,k'th occurance of such an array starting
at the location p.

	*p[i][j][k] = 6;

says place a 6 into the location pointed to by the data at the i,j,k'th
occurance of such an array starting at location p.

The following program will show the compilers interpretation of those
statements:

	main()
	{
		int	(*p) [13][2][4];

		p = (int (*) [13][2][4]) malloc(sizeof(*p));

		(*p) [12][1][3] = 5;

		printf("%d\n", p);
		printf("%d\n", sizeof(p));
		printf("%d\n", sizeof(*p));
		printf("%d\n", p[0][0][1]);
		printf("%d\n", (*p)[12][1][3]);
	}


	4202744		<== value of pointer p
	4		<== size of p
	416		<== size of what p points to
	4202760		<== value of p[0][0][1]      **
	5		<== correct value at 12,1,13

** note that p[0][0][1] is equal to the p (4202744) + sizeof(*p) (416).  Which
is what you should expect.

Also note that *p[12][1][3] caused a core dump since it is way beyond the end
of address space for this program.
-- 
+-----------------------------------------------------------------------+
| Conor P. Cahill     uunet!virtech!cpcahil      	703-430-9247	!
| Virtual Technologies Inc.,    P. O. Box 876,   Sterling, VA 22170     |
+-----------------------------------------------------------------------+



More information about the Comp.lang.c mailing list