Pointers to arrays in C

jrv at siemens.UUCP jrv at siemens.UUCP
Tue Apr 8 01:36:00 AEST 1986




>It *is* a pointer to an array.  Try running this program:
>
>    main()
>    {
>	char (*x)[10];
>	printf("%d\n%d\n%d\n", sizeof(*x), sizeof(x), sizeof((*x)[2]));
>    }
>
>It prints (on a VAX running ULTRIX):
>
>10
>4
>1
>
>So, *x is an object of size 10 (the array), x is an object of size 4 (a
>pointer), and (*x)[2] is a single byte (a char).  C's strange type
>syntax strikes again.
>
>Paul Dietz
>dietz at slb-doll.csnet
>/* End of text from siemens:net.lang.c */


When I learned C an instructor showed me a trick to use to keep straight
in one's mind what a particular data construction was. To find out what
data type something is go back to the original declaration of it cover over
what you have in the expression and what is left is the data type.
For example using the program above.

sizeof(*x)
	char (*x)[10];
cover        ^^^^        and you get an array of 10 characters


sizeof(x)
	char (*x)[10];
cover          ^         and you get a pointer to an array of 10 characters


sizeof((*x)[2])
	char (*x)[10];
cover        ^^^^^^^^	and you get a character


So by this "convention" C's syntax is consistent and the sizeof() operator
worked as I would expect. Admittedly this scheme works easily on simple
data types (hey, it was an intro class :-)) and there are some expressions
which I have seen in net.lang.c on which I did not even attempt it.


Jim Vallino
Siemens Research and Technology Lab.
Princeton, NJ
{allegra,ihnp4,seismo,philabs}!princeton!siemens!jrv



More information about the Comp.lang.c mailing list