我是一名有用的助手,可以为您进行翻译。以下是需要翻译的内容:
客户端代码:
当我尝试使用来自structB的名为"c"的字符串时,该程序会崩溃。无论我尝试打印它还是像上面的示例一样分配整个structB,都没有关系。
问题出在哪里?我应该以不同的方式在服务器端创建message_t *reply吗?
我有一个问题,无法发送由指向包含其他结构体的结构体的指针构建的zmq消息。
服务器代码:
#include <zmq.hpp>
#include <string>
#include <iostream>
using namespace zmq;
using namespace std;
struct structB{
int a;
string c;
};
struct structC{
int z;
struct structB b;
};
int main()
{
context_t context(1);
socket_t *socket = new socket_t(context,ZMQ_REP);
socket->bind("tcp://*:5555");
message_t *request = new message_t();
socket->recv(request);
struct structB messageB;
messageB.a=0;
messageB.c="aa";
struct structC *messageC = new struct structC;
messageC->z = 4;
messageC->b = messageB;
char *buffer = (char*)(messageC);
message_t *reply = new message_t((void*)buffer,
+sizeof(struct structB)
+sizeof(struct structC)
,0);
socket->send(*reply);
return 0;
}
客户端代码:
#include <zmq.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace zmq;
struct structB{
int a;
string c;
};
struct structC{
int z;
struct structB b;
};
int main()
{
context_t context(1);
socket_t *socket = new socket_t(context,ZMQ_REQ);
socket->connect("tcp://*:5555");
const char* buffer = "abc";
message_t *request = new message_t((void*)buffer,sizeof(char*),0);
socket->send(*request);
message_t *reply = new message_t;
socket->recv(reply);
struct structC *messageC = new struct structC;
messageC = static_cast<struct structC*>(reply->data());
cout<<messageC->b.a<<endl;//no crash here
struct structB messageB = messageC->b;//Segmentation fault (core dumped)
return 0;
}
当我尝试使用来自structB的名为"c"的字符串时,该程序会崩溃。无论我尝试打印它还是像上面的示例一样分配整个structB,都没有关系。
问题出在哪里?我应该以不同的方式在服务器端创建message_t *reply吗?
struct
关键字,但在C++中不需要。为什么你有时会使用它?)并且同样奇怪地混合了堆栈和堆分配的对象(为什么你在堆栈上创建messageB
而在堆上创建messageC
?messageC
也可以在堆栈上创建。而且messageB
是messageC
的一部分;你不需要一个单独的实例。) - Jan Hudec