Would anyone please analyze the array problem to me please?

K

kun niu

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.
 
S

Sjouke Burry

kun said:
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.


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

kun niu

kun said:
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.

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

application_pgp-signature_part
< 1K²é¿´ÏÂÔØ

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

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top