in my c++ project I have class with two members. the char array member I have problems with.
class frame_message
{
public:
explicit frame_message(const unsigned int id, const char data[]) :id_(id), data_{ *data }{};
// only the first char 'a' is copied to `data_`
char* get_data() { return data_; };
void get_data(char** data) { *data = data_; };
private:
unsigned int id_; char data_[8];
};
now from main method I want to send another char array used to initialize the class array.
main
{
char data[8]={'a','b','c'} // indexs 3 to 7 are '\0'
char data2[8];
char data3[8];
frame_message myMessage(0xF004,data); // the data is passed as "abc"
data2 = myMessage.get_data(); // analysis error
myMessage.get_data(&data3); // runtime exception
}
How should I initialize the private member of class with exactly the data array send to constructor?
also for for get_data
functions what data type should be passed?
ps I am new in c/c++ and yet get confused in pointers, references and specially char
and char*
For the constructor, it would be a good idea to pass a length parameter as well because you can accept only up to 8 bytes. Then, if your length is <= 8 :
memcpy(data_, data, length)
Same thing in your parameterized get_data, so it would be:
memcpy(*data, data_, 8) /* Assuming that they provide long enough array. */
It is good practice when dealing with arrays to always include length, and when dealing with pointers to check if they are NULL - I'll leave this to you. The reason you were getting errors is because you cannot assign a pointer to a statically declared array - it has a fixed address, you can only change the content.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.