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 <iostream>
#include <array>
typedef unsigned char byte;
int main()
{
std::array<byte, 2> x;
x = { { 78, 82 } };
std::cout.write( reinterpret_cast<char *>( x.data() ), x.size() ) << std::endl;
}
why this code gives an error ?
Because you may not assign to an array variable. Arrays can not be passed by value to functions or operators as such. When used in a context where a pointer is expected, they decay to a pointer to first element.
It's not possible to copy an array (or initializer list) to another using only pointers to the first elements of each array. Such operation requires information about the size of the arrays.
There's a good analysis on why the assignment is not allowed here. It's about array to array assignment, but I suppose it applies to initializer list as well.
while if we intialized the array in one line byte x[2] = {78,82} works correctly ?
It works because you may initialize an array variable (with list initialization in this case). Remember that =
does different things depending on if it's used in a declaration or a non-declaration statement. In a declaration it's syntax for initialization, in non-declaration statement it's the assignment operator.
what is the difference of the x pointer in both cases ?
x
is not a pointer, it's an array. There is only difference is that in one case you initialize the objects in x
and in the other you leave it uninitialized and then attempt to assign an an initializer list to it which is not possible.