Yes, array
decays to pointer implicitly.
Most commonly seen infunction parameters:
1 2 3 4 5 6 7
|
void func( int arr[] ); // syntactic sugar, an alias for:
// void func( int* arr );
int main() {
int sample [42] {};
func( sample ); // only address of first element passes to func
}
|
Note:
1 2
|
char letter[100] = { "Hello World!" };
std::cout << letter;
|
There is no ostream related operator<< that would operate on arrays, but there is one that takes
const char*
.
[edit]
If we don't initialize letter[100], In the following example compiler allocated memory for the sentence?
How can I check if memory is allocated? |
The
char letter[100] ;
allocates memory for continuous block of 100 chars. The value of each char is uninitialized and therefore
undefined.
The
char* sentence = letter;
creates a valid pointer to allocated memory. The pointer remains valid until the letter goes out of scope.
The
std::cout << letter
copies consecutive character values to output until it encounters null character. We have no idea where in memory starting from address of letter[0] there is null, nor how many unprintable values are before it.
The convention with pointers is that address value
nullptr
is considered "does not point to memory" and all other addresses have to be assumed valid. It is the responsibility of programmer to ensure that the pointer is truly valid.
Note:
1 2
|
char letter[100] ;
char* beyond = letter+100;
|
The 'beyond' points after the last element in the array. Out of range. It does not point to allocated memory, but can be used to test whether we have reached that far (when iterating the array).