hypr2 hypr2 - 2 years ago 119
C Question

Clearing char array in C

I have declared

char data[101];
and after that read message from socket into it(server - client communication). After the message is displayed on screen I want to clear/empty that char array. I tried
memset(data, 0, sizeof(data))
bzero(data, sizeof(data));
And I think it still didn't clear it. At the output after receiving the first message I also get some weird characters: ��|V� and after them also the message is shown. Now I don't know if that is from clients or servers side. I tried to clear it on both but the result isn't any different.

This is how I send message:

char data[101];
read(0, data, 101);
dprintf(socket_fd, data);
bzero(data, sizeof(data));

Answer Source

Here is another alternative solution

//Declare and initialize to NUL characters.
char data[101] ="";  

//fgets() will take care of out of boundary issue.
 if (fgets(stdin, data, sizeof(data))
    dprintf(socket_fd, "%s", data);  // Send the data
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download