我在通过套接字发送整数数组时遇到了麻烦。 代码看起来像这样
程序一:(在windows上运行)
int bmp_info_buff[3];
/* connecting and others */
/* Send informations about bitmap */
send(my_socket, (char*)bmp_info_buff, 3, 0);
程序 2:(在中微子上运行)
/*buff to store bitmap information size, with, length */
int bmp_info_buff[3];
/* stuff */
/* Read informations about bitmap */
recv(my_connection, bmp_info_buff, 3, NULL);
printf("Size of bitmap: %d\nwidth: %d\nheight: %d\n", bmp_info_buff[0], bmp_info_buff[1], bmp_info_buff[2]);
它应该打印
位图大小:64
宽度:8
高度:8
位图大小:64
宽度:6
高度:4096
我做错了什么?
最佳答案
当您将 bmp_info_buff
数组作为 char 数组发送时,bmp_info_buff
的大小不是 3,而是 3 * sizeof(int)
同样适用于recv
替换
send(my_socket, (char*)bmp_info_buff, 3, 0);
recv(my_connection, bmp_info_buff, 3, NULL);
通过
send(my_socket, (char*)bmp_info_buff, 3*sizeof(int), 0);
recv(my_connection, bmp_info_buff, 3*sizeof(int), NULL);
关于c++ - 在 C/C++ 中通过套接字发送 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14158564/