I'm learning C++ these days by myself and I have some problem understanding why this code doesn't compiles using #g++ -std=c++11 source.cpp
. Actually it doesn't matter which specific standard I use, it just doesn't compiles.
#include <iostream>
#include <string>
using namespace std;
int print_a(char array[])
{
for(char c : array)
cout << c;
cout << endl;
return 0;
}
int main(void)
{
char hello[] {"Hello!"};
print_a(hello);
return 0;
}
Stumbled across this. In a function you cannot use a range-based loop on an array like this, because the char array[] parameter degrades the array to an address. In other words, when you pass in "hello", to the function it is just getting an address. It can no longer determine the size.
RépondreSupprimerThe way around this is to pass in a reference to the array:
int print_a(char (&array)[1]) // specifiy size in []
Better yet, use a vector or C++ style array.
The