prev up next   top/contents search

comp.lang.c FAQ list · Question 6.13

Q: How do I declare a pointer to an array?


A: Usually, you don't want to. When people speak casually of a pointer to an array, they usually mean a pointer to its first element.

Instead of a pointer to an array, consider using a pointer to one of the array's elements. Arrays of type T decay into pointers to type T (see question 6.3), which is convenient; subscripting or incrementing the resultant pointer will access the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays (see below), and are generally useful only when operating on arrays of arrays, [footnote] if at all. (See also question 6.18.)

If you really need to declare a pointer to an entire array, use something like ``int (*ap)[N];'' where N is the size of the array. (See also question 1.21.) If the size of the array is unknown, N can in principle be omitted, but the resulting type, ``pointer to array of unknown size,'' is useless.

Here is an example showing the difference between simple pointers and pointers to arrays. Given the declarations

int a1[3] = {0, 1, 2};
int a2[2][3] = {{3, 4, 5}, {6, 7, 8}};
int *ip;		/* pointer to int */
int (*ap)[3];		/* pointer to array [3] of int */
you could use the simple pointer-to-int, ip, to access the one-dimensional array a1:
	ip = a1;
	printf("%d ", *ip);
	ip++;
	printf("%d\n", *ip);
This fragment would print
	0 1
An attempt to use a pointer-to-array, ap, on a1:
	ap = &a1;
	printf("%d\n", **ap);
	ap++;				/* WRONG */
	printf("%d\n", **ap);		/* undefined */
would print 0 on the first line and something undefined on the second (and might crash). The pointer-to-array would only be at all useful in accessing an array of arrays, such as a2:
	ap = a2;
	printf("%d %d\n", (*ap)[0], (*ap)[1]);
	ap++;		/* steps over entire (sub)array */
	printf("%d %d\n", (*ap)[0], (*ap)[1]);
This last fragment would print
	3 4
	6 7

See also question 6.12.

Additional links: further reading

References: ISO Sec. 6.2.2.1


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North