I am studying the basics in C and I am confused about the strings and arrays.
#include<stdio.h>
int main()
{
char arr[2][4] = {1,2,3,4,5,6,7,8};
printf("%u %u\n",arr,arr+1);
printf("%d",*(*(arr+1)+2) );
return 0;
}
Here arr
and arr+1
are adjacent locations, but in the second printf
arr+1
goes straight to the zero index element of the second array. How is this legal? I have thought that to go to the second array it should be &arr+1
.
What i learned is --> for one dimensional array:
arr[7]={1,2,3,4,5,6,7};
here arr and &arr should not be considered same(although they print same value, but the sense of this information is completely different) . Thats why arr+1 and &arr+1 will not be same too. &arr gives the address of a data type that is a container of 7 integers thats why &arr+1 goes to the subsequent array type that is also a container of 7 integers . so
arr = 5796 , &arr = 5796 (both are base address but arr is the address of
1st element while &arr is the address of the whole array)
arr+1 = 5800 ,&arr+1 = (5796+(7X4))=5797+28 = 5825(this is address of some
new array)
for two dimensional array the concept is same:
arr[2][4]={1,2,3,4,5,6,7,8};
now arr
is here is also a pointer that points to array individual elements so arr
and arr+1
are the addresses of its successive elements (and those elements are {1,2,3,4}
and {5,6,7,8}
)_
and in the same way &arr
and &arr+1
gives the base addresses of two arrays that have 2x4=8 elements so to &arr
and &arr+1
are addresses of two similar sized arrays one after another.
So
arr = 5796 , arr+1 = 5796+(4*3)=5796+12 = 5808
&arr = 5796 , &arr+1 = 5796+(4*7)=5796+ 28= 5824
Now we can see in 2 dimensional array to reach an individual element there are two addresses associated.
1)ar
r (that gives which element to choose between the two inside arrays)
2)*arr
(that gives which element in that particular element(array)
so we need to dereference two times if we want to reach to the data.
arr=5796(first array), *arr=5796(first element address), **arr = 1 (1st element)
arr+1=5812(second array), *(arr+1) = 5812(first element address), *(*(arr+1))=5(first element)
arr=5796,*arr=5796, *arr+1=5796+1(second element), *(*arr+1)=2 (second element)
now the syntax for arrays:
*arr = arr[0]
**arr = arr[0][0]
*arr+1 = arr[0]+1
**arr+1 = arr[0][0]+1
*(*arr+1) = *(arr[0]+1) = arr[0][1]
*(*(arr+1)+1) = *(arr[1]+1) = arr[1][1]
there are some other ways to write arrays
3[arr[1]] = arr[1][3]
-3[arr[1]] = -arr[1][3]
*(1[arr]+2) = *(arr[1]+2) = arr[1][2]
the concept can be expanded to 3 dimensional array too , but this is the minimum every beginner should understand.Correct me if I am wrong anywhere conceptually or syntactically.