incrementing a pointer to an array

S

subramanian100in

The following portion is from c-faq.com - comp.lang.c FAQ list ·
Question 6.13

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 */\

ap = &a1;
printf("%d\n", **ap);
ap++; /* WRONG */

Here why is incrementing ap ie 'ap++' mentioned as WRONG ? Isn't it
similar to
int i_int = 100;
int *p = &i_int;
p++;

Here we cannot dereference 'p' but incrementing 'p' only once, is
allowed. Similarly,

ap is assigned '&a1'. Then we increment ap only once. Why is this
WRONG ?

Kindly clarify.

Thanks
V.Subramanian
 
R

Richard Tobin

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 */\

ap = &a1;
printf("%d\n", **ap);
ap++; /* WRONG */
Here why is incrementing ap ie 'ap++' mentioned as WRONG ?

Because the next line, which you have omitted, is

printf("%d\n", **ap); /* undefined */

The increment in isolation is not wrong, but if you're intending to
dereference the pointer, it is.

-- Richard
 
M

Martin Ambuhl

The following portion is from c-faq.com - comp.lang.c FAQ list ·
Question 6.13

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 */\

ap = &a1;
printf("%d\n", **ap);
ap++; /* WRONG */

Here why is incrementing ap ie 'ap++' mentioned as WRONG ?

compile and run the following. Your implementation will certainly give
different values and perhaps a different format for the addresses. What
will none the less be true is that when ap = &a, ++ap is not the address
of any element of a. Why? Because ap is not a pointer to int, bur a
pointer to an array[3] of int, and the value of ++ap is the address of
the next array[3] of int.

#include <stdio.h>

int main(void)
{
int a[3] = { 0, 1, 2 };
int (*ap)[3]; /* pointer to array [3] of int */
size_t i, n = sizeof a / sizeof *a;
ap = &a;
printf("sizeof a = %zu, sizeof *a = %zu\n", sizeof a, sizeof *a);
for (i = 0; i < n; i++)
printf("&a[%zu] = %p\n", i, (void *) &a);
putchar('\n');
printf("sizeof ap = %zu, sizeof *ap = %zu\n", sizeof ap,
sizeof *ap);
printf("ap = %p, ", (void *) ap);
printf("++ap = %p\n", (void *) ++ap);
return 0;
}


sizeof a = 12, sizeof *a = 4
&a[0] = dff9c
&a[1] = dffa0
&a[2] = dffa4

sizeof ap = 4, sizeof *ap = 12
ap = dff9c, ++ap = dffa8
 

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
474,262
Messages
2,571,048
Members
48,769
Latest member
Clifft

Latest Threads

Top