简体   繁体   English

在C ++中删除字符数组的内容

[英]deleting the contents of a character array in C++

I have initialized a character array as: char Buffer[1000]={0}; 我已将字符数组初始化为:char Buffer [1000] = {0}; In this array, data is received from a socket and displayed Everytime I display the contents of this array, I want to again initilize all its contents to zero. 在这个数组中,从套接字接收数据并显示每次我显示这个数组的内容,我想再次将其所有内容初始化为零。 If I don't do that and again read data from the socket using the same array, some old data present in array is also displayed. 如果我不这样做并再次使用相同的数组从套接字读取数据,则还会显示数组中存在的一些旧数据。 i used memset() function to again initialize all contents of array with zeros before receiving the data second time, but it didn't work. 我使用memset()函数在第二次接收数据之前再次使用零初始化数组的所有内容,但它不起作用。 Is there any other way of doing that in c/c++ ? 在c / c ++中有没有其他方法可以做到这一点? seeking help :( 寻求帮助:(

The contract for recvfrom doesn't guarantee what happens to the memory in between the end of the message received and the end of the buffer. recvfrom的合同不保证在收到的消息结束和缓冲区结束之间内存会发生什么。 That's why recvfrom returns the number of valid bytes. 这就是recvfrom返回有效字节数的原因。 The remainder of the buffer is not unchanged, it is overwritten with trash. 缓冲区的其余部分不会更改,它会被垃圾覆盖。

Change 更改

memset(receiveBuffer,'\0',1000); 
recv_len = recvfrom(socketIdentifier, receiveBuffer, sizeof(receiveBuffer), 0, (struct sockaddr *) &clientSocket, &clientSocketLength);

to

recv_len = recvfrom(socketIdentifier, receiveBuffer, sizeof(receiveBuffer), 0, (struct sockaddr *) &clientSocket, &clientSocketLength);
if (recv_len > 0)
    memset(receiveBuffer + recv_len, 0, 1000 - recv_len); 

在接收并显示数据后,运行从0到999的循环以重置阵列的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM