Pointer to array of unspecified size

G

Grumble

I've come across code that has me confused. Here it is, stripped down:

#include <stdlib.h>
#include <stdio.h>
#define N 20
int main(void)
{
int (*p)[];
int *q;
int i;
p = malloc(N*sizeof(int));
q = malloc(N*sizeof(int));
for (i=0; i < N; ++i)
{
(*p) = i+666; q = i+666;
}
for (i=0; i < N; ++i)
{
printf("%d == %d\n", ((int *)p), q);
}
return 0;
}

$ gcc-3.4.3 -Wall -ansi -pedantic -O1 testcase.c

I don't understand why anyone would define 'p' that way? Do they want to
make it clear that 'p' will point to an array (not just one element)
sometime in the future? I'd just use 'q'.

It seems strange to have to write (*p) every time I want to access
the i-th element. Moreover, it seems even stranger that (*p) is
equivalent to ((int *)p).

I'd appreciate your comments on this weird (to me) syntax.
 
R

Richard Bos

Grumble said:
I've come across code that has me confused. Here it is, stripped down:
int main(void)
{
int (*p)[];
int *q;
I don't understand why anyone would define 'p' that way? Do they want to
make it clear that 'p' will point to an array (not just one element)
sometime in the future?

Yes. p is a pointer to an array of (an unknown number of) ints. q is a
pointer to int. If you do this:

int *r[];

then r is an array of pointers to int. Pointers to entire arrays are
rarely useful. A pointer to an array of unknown size is, AFAIK,
completely useless.
See also said:
I'd just use 'q'.

So would I.

Richard
 
R

raj

int (*p)[];
is a pointer to int array .the size of the array is undefined at the
time of declaration and can be set to any size after wards.is a pointer to int . it is not a pointer to int array. it can point
to an int variable, i.e nothing but a pointer to an array with only one
element.
we can use this as pointer to integer array by using [] operator or by
pointer arthmetic .
like *( q + i ) .
your code just establishes this fact that 's all.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top