Get a string of an object and assign it to a char

1

In my school activity they asked me to use dimension fields for an activity, what happens is that I keep a "1" in the object and when I want to recover it and assign it to the object it is not possible for me. He tells me it's not constant.

char nombreC[30], artistaC[30], generoC[30], idC[2], estatusC[2]; //Así los declaro

//y así lo quiero recuperar "'s' es mi el nombre de mi objeto"
s.setId("1");
idC = s.getId().c_str();
idLen = stoi(s.getId()); //Para el campo de dimensión

//para después guardarlo en un archivo así
songsList.write((char*)&idLen, sizeof(int));
songsList.write((char*)&idC, idLen);

ERROR:

menu.cpp:53: error: incompatible types in assignment of 'const char*' to 'char [2]'
         idC = s.getId().c_str();
             ^
    
asked by Oscar D 29.08.2018 в 01:25
source

2 answers

1

I guess the type of data that returns this function:

s.getId().c_str();

is a const char*

In C you can not match a type of pointer data, which is the one that returns the function, a pointer that points to the first memory position of the array you return, to an array of two positions directly in that way. You can use the function strcpy , I'll give you an example to see if it works:

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

char * c_str() {
    char *returned_array = (char *)malloc(sizeof(char) * 2); //Esta multiplicado por 2 para reservar 2 bytes, ya que cada caracter ocupa 1 byte

    returned_array[0] = 'a';
    returned_array[1] = 'b';

    return returned_array;
}

int main() {

    char idC[2];
    strcpy(idC, c_str());

    //Al printar los valores obtengo como resultado a y b
    cout << idC[0] << endl;
    cout << idC[1] << endl;

}

(In the function c_str() I have given an example either, what matters is that it returns the same as in your case a char* )

Basically what the strcpy does is, take the pointer of idC that is the one that points to the first position of that array and copy from there all the elements that have the second parameter that you pass.

    
answered by 29.08.2018 / 03:04
source
3

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 .

    
answered by 29.08.2018 в 09:21