Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
1  
Have a look at the related question at stackoverflow: stackoverflow.com/questions/632846/clearing-a-char-array-c ... – user3704293 Jan 11 at 12:07
    
Why are you converting a char array to a String just to print it? Do you realise just how bad that is for the poor little Arduino? hacking.majenko.co.uk/the-evils-of-arduino-strings – Majenko Jan 11 at 12:21

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';
share|improve this answer
    
This clears only the first byte. With = { 0 }; everything is cleared. – ott-- Jan 11 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 at 15:15

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!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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