-
Pointers to array
I have a doubt regarding pointers to array. the following program gives a compilation error if while declaring the pointer i give 'int (* ptr)[3] = arr;' instead of '=&arr'. Why is it so? I am using MS visual studio for compiling the program.
#include<iostream>
using namespace std;
int arr[3] = {1,2,3};
int main()
{
int (* ptr)[3] = &arr;
cout<<"The value of arrays "<<arr[0] <<" "<<arr[1] <<" ";
getchar();
return 0;
}
-
Re: Pointers to array
I'm not sure what you're trying to do there. The correct syntax is
int* ptr = arr;
-
Re: Pointers to array
Not sure what you are trying to do, maybe something like this??
Code:
#include<iostream>
using namespace std;
int arr[3] = {1,2,3};
int main()
{
int* ptr = arr;
cout<<"The value of arrays "<< arr[0] <<" "<< arr[1] <<" " << arr[2] << endl;
*ptr = 4;
*( ptr + 1 ) = 5;
ptr[2] = 6;
cout<<"The value of arrays "<< arr[0] <<" "<< arr[1] <<" " << arr[2] << endl;
getchar();
return 0;
}
-
Re: Pointers to array
I was trying to understand two concepts here
1. pointers to arrays
2. name of array is actually a pointer to the first element of the array. basically it is a address.
I understand that
int (* ptr)[3] = arr;
causes a compilation error because the left hand side of the expression is a pointer to array of 3 intergers and right hand side is just a integer pointer. So I can see type incompatibitily in this statement.
But i am not able to explain how can a statement like the following be logically correct though the program works fine if I use it
int (* ptr)[3] = &arr;
the left hand side of the expression is a pointer to array of 3 intergers and right hand side is just address of a integer pointer.
-
Re: Pointers to array
I'd say it's because with just "arr", automatic type conversion has the array decay into a pointer to its first value, with the type int*. The declaration "int (* ptr)[3]" specifically needs a pointer to an array of three ints, so the types are incompatible. Apparently when you specifically take the address of the array using "&arr", the compiler is able to identify it as a three element array and do the assignment.
The whole pointer to array thing though... I don't think I've ever actually used it. It sort of defeats the purpose of pointers, I think.
-
Re: Pointers to array
There is one and only one case where a reference to an array may be useful: it allows you to use templates to automatically deduce the size of the array.
In just about all other cases, simply allow the name of the array to decay to a pointer and you have what you need. Remember to always pass the size of the array separately, as you won't be able to get that via sizeof() once it has decayed!