I'm not sure if this is a good question by community standards (let me know if there is a better way or place for this question please).
I'm working on understanding a piece of code which I've come across while trying to learn C++. Code is as follows:
MessageHdr *msg;
size_t msgsize = sizeof(MessageHdr) + sizeof(joinaddr->addr) + sizeof(long) + 1;
msg = (MessageHdr *) malloc(msgsize * sizeof(char));
// create JOINREQ message: format of data is {struct Address myaddr}
msg->msgType = JOINREQ;
memcpy((char *)(msg+1), &memberNode->addr.addr, sizeof(memberNode->addr.addr));
memcpy((char *)(msg+1) + 1 + sizeof(memberNode->addr.addr), &memberNode->heartbeat, sizeof(long));
emulNet->ENsend(&memberNode->addr, joinaddr, (char *)msg, msgsize);
- What is the point of casting to
MessageHdr *
in line 3? - I feel like we're building a
char[]
. We're just usingMessageHdr*
to refer (to point) to it but I am not sure why? Wouldn't achar*
be a better choice?
Receiving code is as follows (shortened):
int EmulNet::ENsend(Address *myaddr, Address *toaddr, char *data, int size) {
en_msg *em;
...
em = (en_msg *)malloc(sizeof(en_msg) + size);
em->size = size;
memcpy(&(em->from.addr), &(myaddr->addr), sizeof(em->from.addr));
memcpy(&(em->to.addr), &(toaddr->addr), sizeof(em->from.addr));
memcpy(em + 1, data, size);
...
I'm beyond confused at this point - sorry for the vague question. Is this idiomatic C++? I feel as if this could have been done in much cleaner ways instead of passing around a char[]
and referencing it via pointers of random struct types.
I guess what I'm ultimately trying to ask is, while I kind of understand the code, it feels very unnatural. Is this a valid/common approach of doing things?
EDIT
MessageHdr is a struct as follows:
typedef struct MessageHdr {
enum MsgTypes msgType;
}MessageHdr;
joinaddr is a class intances:
class Address {
public:
char addr[6];
Address() {}
// Copy constructor
Address(const Address &anotherAddress);
// Overloaded = operator
Address& operator =(const Address &anotherAddress);
bool operator ==(const Address &anotherAddress);
Address(string address) {
size_t pos = address.find(":");
int id = stoi(address.substr(0, pos));
short port = (short)stoi(address.substr(pos + 1, address.size()-pos-1));
memcpy(&addr[0], &id, sizeof(int));
memcpy(&addr[4], &port, sizeof(short));
}
string getAddress() {
int id = 0;
short port;
memcpy(&id, &addr[0], sizeof(int));
memcpy(&port, &addr[4], sizeof(short));
return to_string(id) + ":" + to_string(port);
}
void init() {
memset(&addr, 0, sizeof(addr));
}
};