Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearing a char array c

Tags:

arrays

c

char

I thought by setting the first element to a null would clear the entire contents of a char array.

char my_custom_data[40] = "Hello!"; my_custom_data[0] = '\0'; 

However, this only sets the first element to null.

or

my_custom_data[0] = 0;  

rather than use memset, I thought the 2 examples above should clear all the data.

like image 540
ant2009 Avatar asked Mar 11 '09 00:03

ant2009


People also ask

How do I empty a char string?

If you want to "empty" it in the sense that when it's printed, nothing will be printed, then yes, just set the first char to `\0'.

How do you delete a char array in Arduino?

To reset a cstring simply set the value of the first index to 0 (or '\0'). Assuming tempChars holds: "HOME,1.375", the value of rpiCommand after the (2) statement is "1.375" which does not have a "HOME" in it. Perhaps what you want to replace the (2) statement by: strcpy(rpiCommand, tempChars);


1 Answers

It depends on how you want to view the array. If you are viewing the array as a series of chars, then the only way to clear out the data is to touch every entry. memset is probably the most effective way to achieve this.

On the other hand, if you are choosing to view this as a C/C++ null terminated string, setting the first byte to 0 will effectively clear the string.

like image 144
JaredPar Avatar answered Sep 21 '22 23:09

JaredPar