C++ Implicit Conversions with Array

Introduction

Arrays are implicitly convertible to pointers.

When we assign an array name to the pointer, the pointer points at the first element in an array.

Example:

#include <iostream> 

int main() 
{ 
    int arr[5] = { 1, 2, 3, 4, 5 }; 
    int* p = arr; // pointer to the first array element 
    std::cout << *p; 
} 

In this case, we have an implicit conversion of type int[] to type int*.

When used as function arguments, the array gets converted to a pointer.

More precisely, it gets converted to a pointer to the first element in an array.

In such cases, the array loses its dimension, and it is said it decays to a pointer.

Example:

#include <iostream> 

void myfunction(int arg[]) 
{ 
    std::cout << arg; //from w ww .j a  v a2s.  co  m
} 
int main() 
{ 
    int arr[5] = { 1, 2, 3, 4, 5 }; 
    myfunction(arr); 
} 

Here, the arr argument gets converted to a pointer to the first element in an array.

Since arg is now a pointer, printing it outputs a pointer value similar to the 012FF6D8.

Not the value it points to To output the value it points to we need to dereference the pointer:

#include <iostream> 

void myfunction(int arg[]) 
{ 
    std::cout << *arg; //from   w  w w  .j  av  a 2 s  .  co  m
} 

int main() 
{ 
    int arr[5] = { 1, 2, 3, 4, 5 }; 
    myfunction(arr); 
} 

That being said, it is important to adopt the following: prefer std:vector and std::array containers to raw arrays and pointers.




PreviousNext

Related