0

Currently I convert the characters in char received[20] to string using String randomString(received) and I am able to display it using Serial.println(randomString). After displaying the string, I would like to know the easiest way to clear out its contents.

| improve this question | | | | |
1

In C and C++ a null terminated array of characters is a string (although not a String). Many routines for reading input terminate the result with a null as does an assignment like"

char foo[] = "This is a string.";

All you would need to do to "clear" this string is to assign a null to the first character. For example:

foo[0] = '\0';
| improve this answer | | | | |
  • This clears only the first byte. With = { 0 }; everything is cleared. – ott-- Jan 11 '16 at 14:29
  • For C (null terminated) strings, if the first character is a null, then the string is empty or clear. Functionally that solves the problem, but if there are security concerns then you are right that the whole string should be cleared. – dlu Jan 11 '16 at 15:15
1

First version with conversion from char[] to Arduino String class:

char received[20];
...
// Some code that assigns received
...
String randomString(received); 
Serial.println(randomString);

// Clear string
randomString = "";

Second version without the Arduino String class:

char received[20];
...
// Some code that assigns received
...
Serial.println(received);

// Empty received buffer
received[0] = 0;

And third version where the buffer is cleared:

char received[20];
...
// Some code that assigns received
...
Serial.println(received);

// Clear received buffer
memset(received, 0, sizeof(received)); 

Cheers!

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.