On Wed, 17 Aug 2005 13:57:40 +0000, Simon Morgan wrote:
> Can somebody please explain why the following piece of code generates an
> error unless I change q[top--] to *q[top--]:
>
> typedef int Queue[10];
> int top = 9;
>
> void insert(Queue *q, int n) {
> q[top--] = n;
> }
>
> $ gcc -c test.c
> test.c: In function `insert':
> test.c:5: error: incompatible types in assignment
>
> Seeing as q is essentially a pointer to an array I assumed that I could
> use array notation but I'm obviously mistaken so I'd just like to know why
> it doesn't work.
You are right that you can use array notation on the pointer, but since it
points to an array of 10 int, indexing it results in a member with type
array of 10 int.
In other words, q[i], which is equivalent to *(q + i), has type int[10],
to which you are attempting to assign a single int. Hence gcc complaining
about incompatible types.
I am going to assume that you are calling insert with the first parameter
being something like &myqueue where myqueue is declared Queue myqueye;
If that's the case, then the problem is not solved by *q[top--] since
that is equivalent to *(q[top--]) when what you want is (*q)[top--].
In other words, q[top--] results in the 10th (when in fact there is only
one) 10-int array, and applying * to it gives the first element of that
10-int array. Whereas (*q) results in the first (and only) 10-int array,
and indexing that with [top--] gives the 10th int in that 10-int array.
If my assumption is correct then there is no reason for you to pass a
pointer to an array in the first place; you should just pass in the array
itself. This will decay to a pointer as always but that pointer when
indexed will result in a member with type int rather than int[10].
So my advice is to change parameter Queue *q to Queue q unless you have a
good reason not to.
--
http://members.dodo.com.au/~netocrat