I\'m beginner to c++
I think this is trivial question but I didn\'t find answer
why this code gives an error ? while if we intialized the array in one line byt
Arrays do not have assignment operators. You have to copy element by element from the source array to the destination array for example by means of standard algorithm std::copy
or using standard C function memcpy
or writing your own loop for the task. Or you can set individual elements of an array using the subscript operator.
However the Standard allows to initialize arrays with initializer lists as any other aggregates when they are defined
byte x[] = { 78, 82 }; // valid
x = { 78, 82 }; // compilation error
Also this statement
cout << x << endl;
does not make sense because this array is not zero-terminated that can result in undefined behaviour.
However you can use standard class std::array
that has the copy assignment operator because it is a class and the compiler implicitly generates this operator for it.
For example
#include
#include
typedef unsigned char byte;
int main()
{
std::array x;
x = { { 78, 82 } };
std::cout.write( reinterpret_cast( x.data() ), x.size() ) << std::endl;
}