Pointer To Array etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Pointer To Array etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

22 Şubat 2019 Cuma

Pointer To Array

Giriş
Array'e pointer elde etmek için
array
&array
&array[0]
kullanılabilir.

Görsel olarak şöyledir.
+----------+----------+----------+----------+----------+
| array[0] | array[1] | array[2] | array[3] | array[4] |
+----------+----------+----------+----------+----------+
^
|
&array[0]
|
&array
Örnek
Şöyle yaparız. p pointer to array ve daha sonra istesek başka bir yere de point ettirebiliriz.
int a[5] = {1,2,3,4,5}
int * p = a;
Örnek
Şöyle yaparız.
int array[5] = { 10,11,12,13,14};

std::cout << array << std::endl;
std::cout << &array << std::endl;
std::cout << &array[0] << std::endl;
Örnek
Şu ise derlenmez.
int a[5] = {1,2,3,4,5};
int*& ref = a;
Açıklaması şöyle
a is not a pointer, it is an array. It has the type int[5]. What it can do it is decay to a pointer int*, which is what happens in the first case. So, taking a reference to p is ok.

Now for the second case. Remember that a is not a pointer. So, there is an implicit conversion happening from int[5] to int*. The result of that conversion is a prvalue. But you can't bind a non-const lvalue reference (which is what ref is) to an rvalue! So the code fails to compile.
Örnek
Pointer To Array'in adresini almak. Elimizde şöyle bir kod olsun.
int *pArray = new int[5];

std::cout << pArray << std::endl; //İlk elemanın adresi
std::cout << &pArray << std::endl; //Pointer'ın adresi
std::cout << &pArray[0] << std::endl;//İlk elemanın adresi
Görsel olarak şöyledir.
+--------+       +-----------+-----------+-----------+-----------+-----------+-----+
| pArray | ----> | pArray[0] | pArray[1] | pArray[2] | pArray[3] | pArray[4] | ... |
+--------+       +-----------+-----------+-----------+-----------+-----------+-----+
^                ^
|                |
&pArray          &pArray[0]