I am a cpp beginner and have been experimenting with come very basics. I was exploring how are reference and pointer different from each other in regards to arrays and wrote a simple snippet.
int main() {
//char * c2 = "C";
//std::cout << &c2<<std::endl;
//std::cout << *c2<<std::endl;
int arr[]={21,2,3,4,5,6,7,8,9,10};
int (&ar)[10]=arr;
int *ar1=arr;
std::cout<<"add of arr[0] :"<<&arr[0]<<std::endl;
std::cout<<"value of ar: "<<ar<<std::endl;
std::cout<<"value of ar1: "<<ar1<<std::endl;
std::cout<<"value of *ar: "<<*ar<<std::endl;
std::cout<<"value of *ar1: "<<*ar1<<std::endl;
std::cout<<"value of *(ar+1): "<<*(ar+1)<<std::endl;
std::cout<<"value of *(ar1+1): "<<*(ar1+1)<<std::endl;
std::cout<<"value of ar[0]: "<<ar[0]<<std::endl;//some garbage value
std::cout<<"value of ar1[0]: "<<ar1[0]<<std::endl;//some garbage value
std::cout<<"value of sizeof(ar): "<<sizeof(ar)<<std::endl;
std::cout<<"value of sizeof(int): "<<sizeof(int)<<std::endl;
std::cout<<"value of sizeof(arr): "<<sizeof(arr)<<std::endl;
std::cout<<"value of sizeof(ar1): "<<sizeof(ar1)<<std::endl;
}
the following is the output for this code:
add of arr[0] :0x7fffe6054ba0
value of ar: 0x7fffe6054ba0
value of ar1: 0x7fffe6054ba0
value of *ar: 21
value of *ar1: 21
value of *(ar+1): 2
value of *(ar1+1): 2
value of ar[0]: 21
value of ar1[0]: 21
value of sizeof(ar): 40
value of sizeof(int): 4
value of sizeof(arr): 40
value of sizeof(ar1): 8
as you can see , the only difference I can spot is the size of reference is different than the size of pointer. In fact value of both reference and pointer is the first element of the array. Even the pointer arithmetic works the same way for both of them. The size of reference is int*10 vs size of pointer which is 8. What is going on here exactly ? How are these two different and is there a standard practise as to when to use a reference or a pointer ?