【发布时间】:2018-11-22 06:51:34
【问题描述】:
如果我有一个结构数组怎么办。我可以通过套接字发送一个结构数组吗?结构大小将不断更新,我可以随时打印出结构的内容。我希望这是有道理的,我的解释可能不会被清除。我的语法在某些领域肯定不正确,它只是我认为它看起来像的一个 sn-p。我只是需要一些指导。
这将通过套接字发送结构数组。
void sendOpenMessage(int num0, int num1, int num2){
struct openMessage{
int num0;
int num1;
int num2
};
struct openMessage open[100];
int i = 0;
open[i].num0 = 1;
open[i].num1 = 2;
open[i].num2 = 3;
int length = sizeof(open);
if(send(socket, &open[i], length, 0) == -1){
fprintf(stderr, "Send() failed");
}else{
printf("Open message is being sent\n");
}
i++;
}
这将接收结构并在消息中显示内容
struct openMessage open[100];
if(recv(clnSocket, &open, sizeof(open), 0) < 0){
fprintf(stderr,"Recv() failed\n");
printf("Error code: %d\n", errno);
}
//Get size of the current struct
//Print out the messages from the structs that have messages?
void printStruct(struct openMessage open){
for(int i = 0; i < sizeof(the struct); i++){
printf("%d\n",open[i].num0);
printf("%d\n", open[i].num1);
printf("%d\n", open[i].num2);
}
}
【问题讨论】:
-
请先尝试。如果您遇到一些特定的错误或问题,那么非常欢迎您提出这个问题。还请查看how to ask good questions 和this question checklist。不要忘记如何创建minimal reproducible example。
-
@Someprogrammerdude 我做到了。以这种方式实现它。我遇到了一堆错误,例如“下标值既不是数组也不是指针也不是向量结构 - Google 搜索”。目前我现在所拥有的只是通过套接字传递一个 typedef 套接字。
-
@Someprogrammerdude 但感谢您提供的提示以供将来使用。我很感激。
-
如果您询问构建错误,那么除了 minimal reproducible example 还向我们展示编译器的 complete 和 full 输出,复制粘贴作为问题中的文本。并在代码中用 cmets 标出错误所在的位置。如果您遇到运行时错误或崩溃或意外结果,请learn how to debug your programs。并告诉我们输入、预期的和实际输出。或者指出代码中崩溃的位置。否则,我们真的无法为您提供太多帮助。
-
我猜,实际错误出在未公开的代码中。如果
struct openMessage open[100];是调用recv()的函数中的局部变量,则在离开该函数后其存储将丢失。返回的指向该数组的指针变得悬空。稍后使用它(例如,使用该指针调用printStruct())将是未定义的行为。同意:需要minimal reproducible example 才能充分回答这个问题。