Home > Blockchain >  Strange behaviour of arr[] in case when arr is a 2d array
Strange behaviour of arr[] in case when arr is a 2d array

Time:01-11

I was learning about 2D arrays and pointer representation of it and all. I ran the following to get the internal working of 2d arrays. I got strange results for the arr2d[0]

    int arr2d[2][3]{{1,2,3},{4,5,6}};
    cout<<"&arr2d[0][0] :"<<&arr2d[0][0]<<endl;
    cout<<"(&(arr2d[0])) :"<<(&(arr2d[0]))<<" arr2d[0] :"<<arr2d[0]<<endl;
    cout<<"*(arr2d[0]) :"<< *(arr2d[0])<<" *(&(arr2d[0])) :"<<*(&(arr2d[0]))<<endl;

output:

&arr2d[0][0] :0x3e6d7ff6c0
(&(arr2d[0])) :0x44efbffbe0 arr2d[0] :0x44efbffbe0
*(arr2d[0]) :1 *(&(arr2d[0])) :0x44efbffbe0

How can *(arr2d[0]) have 1 as output, if arr2d[0] is "circularly pointing" itself? Also apparently pointer arthimetic is not functioning for arr[0], as arr[0] 1 doesn't gets one to arr[1].

I was not expecting the arr[0] to be circularly pointing to itself, I expected it to a pointer to a 1D array of length 3. this tells that this happens but I want to know why how can arr[0] point to itself but at the same time *(arr[0]) gives 1?

CodePudding user response:

How can *(arr2d[0]) have 1 as output, if arr2d[0] is "circularly pointing" itself?

It's not pointing to itself. Arrays are not pointers, but like any variable they do have an address, and the address of an array is the same as the address of the first element. This extends to multidimensional arrays, so arr2d, arr2d[0], and arr2d[0][0] all have the same address, although their types are different.

apparently pointer arthimetic is not functioning for arr[0], as arr[0] 1 doesn't gets one to arr[1].

arr2d[0] decays to &arr2d[0][0], so aarr2drr[0] 1 is &arr2d[0][0] 1 which is the same as arr2d[0][1]. Had you used the expression arr2d 1, that would be the same as &arr2d[0] 1 which gives you arr2d[1]

  • Related