I've been playing around a bit with arrays and a few question have arisen that I hope someone on here can help answer.
1. Sizeof
Code:
void foo( int array[] )
{
cout << sizeof(array) << endl;
cout << sizeof(array[0]) << endl;
}
int main()
{
int b[4] = {1,2,3,4};
cout << sizeof(b) << endl;
cout << sizeof(b[0]) << endl;
cout<<"---------" << endl;
foo(b);
}
The above outputs
16
4
-----
4
4
Im just curious why they the output from main is different from the foo() method ?
2. The below code both store the values 1,2,3,4 just the same way in memory.
Code:
int a[2][2] = {{1,2}, {3,4}};
int b[4] = {1,2,3,4};
if I do
Code:
int* ptr = b;
for(int x=0; x < 4; x++)
cout << *ptr++ << endl;
that works great, however if I do
Code:
int* ptr = a;
for(int x=0; x < 4; x++)
cout << *ptr++ << endl;
I get an 'cannot conver int' error on the first line. I though both a and b array where const pointers to the first element of each array and then there shouldnt be an problem copying the address into a pointer and using the pointer to access the values, but this doesnt seem to work so I guess it's not that simple. Would appreciate if anyone could shed some light on this.
3. If I have the following main code..
Code:
int main()
{
int a[2][2] = {{1,2},{3,4}};
foo(a);
}
is this the only way foo would work
Code:
void foo( int array[][2] )
{
// code..
}
4. When a compiler processes the below code
Code:
int a[2][2] = {{1,2}, {3,4}};
int b[4] = {1,2,3,4};
does it store any additonal data for the 2d array ? Like i.e. row length. Atleast in memory they seem to store the data the same in the same order. Im just wondering how they are different.
I'm interested in the difference between i.e. 1d array and a 2d array. So if anyone knows any good tutorials or articles please add the link.
Thanks for any help.