Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Would anyone please analyze the array problem to me please?

2 views
Skip to first unread message

kun niu

unread,
Jun 4, 2009, 9:56:04 PM6/4/09
to
Dear all,
I've got the following code:
int main()
{
int *a[6][3];
cout<<(a[5]-a[2])<<endl;
cout<<a[5]<<" "<<a[2]<<endl;
return 0;
}
But the output is like this:
9
0xbff44854 0xbff44830
I know that 9 comes from (5-2)*3.
But why is the output here not 36 but 9?

Thanks for any attention and appreciate your answer in advance.

Sjouke Burry

unread,
Jun 4, 2009, 10:29:21 PM6/4/09
to


You have not initialized anything, so what do you expect??
Those variables you used, contain random trash.

Sam

unread,
Jun 4, 2009, 10:58:31 PM6/4/09
to
kun niu writes:

Given the following declaration:

int *a;

With the given declaration, ++a does not increment the address value of 'a'
by 1, but rather by sizeof(int), so that the memory address "++a" points to
the next, following, int in memory.

a+1 returns the same value: not the memory address of 'a' plus 1, but a
memory address of the next int, after 'a'.

Similarly: given two pointers:

int *a, *b;

Presuming that both a and b are pointing to elements of the same array,
the expression (b-a) does not result in the difference between the memory
addresses of b and a, but that difference divided by sizeof(int).

This is so that:

int c=b-a;

This gives the number of ints between a and b, not the number of bytes
between a and b, so that "a+c" returns the same pointer as 'b', or, in other
words:

(b-a) + a == b

James Kanze

unread,
Jun 5, 2009, 7:09:22 AM6/5/09
to
On Jun 5, 4:29 am, Sjouke Burry <burrynulnulf...@ppllaanneett.nnll>
wrote:

> kun niu wrote:
> > Dear all,
> > I've got the following code:
> > int main()
> > {
> > int *a[6][3];
> > cout<<(a[5]-a[2])<<endl;
> > cout<<a[5]<<" "<<a[2]<<endl;
> > return 0;
> > }
> > But the output is like this:
> > 9
> > 0xbff44854 0xbff44830
> > I know that 9 comes from (5-2)*3.
> > But why is the output here not 36 but 9?

Because on your machine, pointers are 4 bytes?

> > Thanks for any attention and appreciate your answer in
> > advance.

> You have not initialized anything, so what do you expect??


> Those variables you used, contain random trash.

He doesn't actually use the variables except for address
calculations, so it doesn't matter that they're not initialized.

--
James Kanze (GABI Software) email:james...@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

kun niu

unread,
Jun 5, 2009, 7:44:21 AM6/5/09
to
> application_pgp-signature_part
> < 1K查看下载

Thank you for your detailed explanation.
The answer is really what I need.:)

0 new messages