pointer and array

Z

Zhang Yuan

I have a question : p point to int
why p+1==&a[1]
not p+1==&a[0][1]
Thank you.
code below :

{int n = 4, m = 3;
int a[n][m];
int (*p)[m] = a; // p == &a[0]
p += 1; // p == &a[1]
(*p)[2] = 99; // a[1][2] == 99
n=p-a; //n==1
}
 
E

Eric Sosman

I have a question : p point to int
why p+1==&a[1]
not p+1==&a[0][1]
Thank you.
code below :

{int n = 4, m = 3;
int a[n][m];
int (*p)[m] = a; // p == &a[0]
p += 1; // p == &a[1]
(*p)[2] = 99; // a[1][2] == 99
n=p-a; //n==1
}

Pointers advance in units of the pointed-at type. Your
pointer `p' points at "an array of `m' ints," so `p+1' points
at "the next array of `m' ints."

Also, note that `p+1' and `&a[0][1]' cannot be the same,
because they have different types. `p+1' is a pointer to "an
array of `m' ints," while `&a[0][1]' is a pointer to "an int."

See Question 6.13 at the comp.lang.c Frequently Asked
Questions (FAQ) page, <http://www.c-faq.com/>. It might be
helpful to review all of Section 6 while you're there.
 
B

BartC

Zhang Yuan said:
I have a question : p point to int
why p+1==&a[1]
not p+1==&a[0][1]
Thank you.
code below :

{int n = 4, m = 3;
int a[n][m];
int (*p)[m] = a; // p == &a[0]

What is the type of p (in English!)? Cdecl tells me it is a pointer to an
array of m ints.

Perhaps try just int *p instead. For initialisation, use &a[0][0] to be
clear (although a[0] will probably work).
 
V

Varun Tewari

what u r trying to achieve and doing are different.
you simply need int *p=a; and then do p+1, which will work as you expect it to be.
 

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,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top