|
-
March 21st, 2010, 07:12 PM
#1
A noob question on arrays:
If I declare an array int a[20][20], then will a[9] be the pointer to the 1st element of the 10th row?
Or is it illegal to say a[9]?
Thanks!
-
March 21st, 2010, 07:30 PM
#2
Re: A noob question on arrays:
 Originally Posted by sgsawant
If I declare an array int a[20][20], then will a[9] be the pointer to the 1st element of the 10th row?
Write a program and find out.
Code:
#include <iostream>
int a[20][20];
int main()
{
std::cout << &a[9] << "\n";
std::cout << &a[9][0] << "\n";
}
What results did you get?
Regards,
Paul McKenzie
-
March 21st, 2010, 07:42 PM
#3
Re: A noob question on arrays:
:P
Thanks!
It's indeed the same!
-
March 21st, 2010, 07:46 PM
#4
Re: A noob question on arrays:
#include <iostream>
int a[20][20];
int main()
{
std::cout << a[9] << "\n";
std::cout << &a[9] << "\n";
std::cout << &a[9][0] << "\n";
system("pause");
}
Interestingly the above code prints all the 3 numbers to be the same. Thus a[9] is an address as much as &a[9] is and also it is the same address!
-
March 21st, 2010, 08:56 PM
#5
Re: A noob question on arrays:
Yes, arrays on the stack have the curious property that since the location of the array is implicit relative to the stack pointer, it does not need to be stored separately. However, the name of an array must be convertible to a pointer to the array. Therefore, the value of the array name----while in some sense meaningless----is chosen to be the address of the first element.
Note, however, that while &a[9] and &a[9][0] may have the same value in this case, the *type* is not the same.
-
March 21st, 2010, 10:38 PM
#6
Re: A noob question on arrays:
Thanks! So basically it's the best to be as clear as possible - esp. if one is ready to punch in those extra characters.
Please correct if wrong.
-
March 22nd, 2010, 08:26 AM
#7
Re: A noob question on arrays:
It's always best to be as clear as possible. Additionally, writing &a[9][0] instead of just a[9] is better because although the two expressions have the same type and value in *this* case, only the first one will continue to work in exactly the same way if you changed the type of a from an int[20][20] to a std::vector< std::vector<int> > for some reason.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|