First you must understand the error that the compiler informs you:
incompatible types in assignment of 'const char*' to 'char [2]'
The compiler is telling you that you can not assign a const char*
to a char [2]
in this statement:
// vvvvv <--- getId devuelve std::string, c_str() devuelve const char*
idC = s.getId().c_str();
// ~~~ <--- idC es char [2]
Effectively you can not assign a pointer ( const char*
) to a formation 1 of characters, the reason (apart from being different types) is the category of the memory they point to .
Static size formations.
The static size formations have the following format:
tipo nombre[tamaño];
The size of the formation must be a constant value known at compile time, the memory occupied by this formation is assigned to the stack and is anchored to the area in which it is created (it is automatically released when it leaves the scope) ).
Dynamic memory.
Dynamic memory in C ++ can only be accessed through pointers, so in the code we will see it as:
tipo *nombre;
There is no record of the amount of memory pointed to by the pointer (data size) and it is housed in the heap without being anchored to any scope, it must be requested and released by the programmer.
Your code.
Apart from not being able to assign two incompatible types to each other, as we have seen, you can not assign memory that belongs to different categories, and that is the reason for the compilation failure. You have the option to copy the data from one side to the other:
const auto &id = s.getId();
std::copy(std::begin(id), std::end(id), std::begin(idC));
// ~~~~~~~~~ ~~~~~~~ ~~~~~~~~~~
// ^ ^ ^
// | | |
// copia desde hasta a partir de
Or better yet, use the same types of data and forget the problems of handling memory by hand:
std::string idC;
s.setId("1");
idC = s.getId();
idLen = stoi(idC);
songsList.write(reinterpret_cast<const char*>(&idLen), sizeof(idLen));
songsList.write(idC.c_str(), idLen);
Also known as array or in English array .