Re: incrementing a pointer to an array
- From: Martin Ambuhl <mambuhl@xxxxxxxxxxxxx>
- Date: Sat, 30 Aug 2008 04:41:17 -0400
subramanian100in@xxxxxxxxx, India wrote:
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[i]);
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
.
- References:
- incrementing a pointer to an array
- From: subramanian100in@xxxxxxxxx, India
- incrementing a pointer to an array
- Prev by Date: Re: incrementing a pointer to an array
- Next by Date: Re: char**
- Previous by thread: Re: incrementing a pointer to an array
- Next by thread: Re: char**
- Index(es):
Relevant Pages
|