Pages

Wednesday, October 4, 2017

Easy tutorial for C / C ++ - Arrays 2 (One dimensional array and pointer)

Easy tutorial for C / C ++ - Arrays 2 (One dimensional array and pointer)

Let's take a look at an example of arrays, addresses, and pointers.

Example Code

#include <iostream>
using namespace std;

int main() {
      int arr[5] ;

      arr[0] = 1 ;
      arr[1] = 2 ;
      arr[2] = 3 ;
      arr[3] = 4 ;
      arr[4] = 5 ;

      for(int i = 0; i < 5; i++){
        cout << "  arr[" << i << "] = " << arr[i] << ", address : "<< &arr[i] << endl;
          }
      return 0;
}

- We declared array 'arr' with 5 integer data and assigned 1, 2, 3, 4, 5 to each element. We will print the value and address of each element through the for loop.

results :

  arr[0] = 1, address : 0x7ffe18c61510
  arr[1] = 2, address : 0x7ffe18c61514
  arr[2] = 3, address : 0x7ffe18c61518
  arr[3] = 4, address : 0x7ffe18c6151c
  arr[4] = 5, address : 0x7ffe18c61520

- The value and address of each element are output. If you look at the characteristics of the address value, you can see that it is increased by exactly 4. Because it is an array with integer data, each space is sequentially allocated by 4 bytes.

Array Name :

- To obtain the element value of an array, you can use the array name and index. (ex: arr [1]) The name of the array acts as a pointer to the start address of the array.
- In the example above, 'arr' will give the same result as '& arr [0]'. Because the name of the array is a pointer, '* arr' also means the value of the first element in the array. ('* arr' == 'arr [0]'). Let's look at an example.

Example Code

#include <iostream>
using namespace std;

int main() {
        int arr[5] ;
   
        arr[0] = 1 ;
        arr[1] = 2 ;
        arr[2] = 3 ;
        arr[3] = 4 ;
        arr[4] = 5 ;

        cout << "  *arr   = " << *arr  << ",  arr    = "<< arr << endl;
        
        for(int i = 0; i < 5; i++){
         cout << "  arr[" << i << "] = " << arr[i] << ", &arr[" << i << "] = "<< &arr[i] << endl;
          }
        return 0;
}

results :

 *arr   = 1,  arr    = 0x7ffeec0a8ea0
  arr[0] = 1, &arr[0] = 0x7ffeec0a8ea0
  arr[1] = 2, &arr[1] = 0x7ffeec0a8ea4
  arr[2] = 3, &arr[2] = 0x7ffeec0a8ea8
  arr[3] = 4, &arr[3] = 0x7ffeec0a8eac
  arr[4] = 5, &arr[4] = 0x7ffeec0a8eb0

- The name of the array ('arr') points to the address value ('& arr [0]') of the first element of the array. And you can see that the value of '* arr' is the same as the value of 'arr [0]'.

No comments:

Post a Comment