Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way of clearing a char array in C/C++?

Tags:

c++

arrays

c

I've been searching for ways of emptying a char array in C/C++. I have come up with this code:

char testName[20];   

for(int i = 0; i < sizeof(testName); ++i)
{
  testName[i] = (char)0;
}  

It has been working for a while now but when I try to strlenthe result is always two more than the typed in word. For instance I input the word dog the output would be five. Why is that so? Is my char array not cleared?

Here is my code:

char testName[20];
void loop()
{
  if(Serial.available())
  {
    Serial.println("Waiting for name...");
    index = 0;
    for(int i = 0; i < sizeof(testName); ++i)
    {
        testName[i] = (char)0;
    }
    while(Serial.available())
    {
      char character = Serial.read();
      testName[index] = character;
      index++;
    }
    Serial.print("Name received: ");
    Serial.println(testName);
    Serial.print("The sentence entered is ");
    Serial.print(strlen(testName));
    Serial.println(" long");
    delay(1000);
  } 
  delay(1000);
}

Screenshot of the output:

Screenshot of the output

Output as text:

Name received: dog

The sentence entered is 5 characters long
like image 498
Xirb Avatar asked Feb 09 '18 16:02

Xirb


2 Answers

Don't use C style arrays in modern C++. When you require a fixed size array, use std::array instead. From a memory storage point of view, they are identical.

You can then clear the array with: myarray.fill('\0')

like image 180
doron Avatar answered Oct 03 '22 21:10

doron


If your definition of "emptying char array" is set all elements of an array to zero, you can use std::memset.

This will allow you to write this instead of your clear loop:

const size_t arraySize = 20;  // Avoid magic numbers!
char testName[arraySize];
memset(&(testName[0]), 0, arraySize);

As for "strange" results of strlen():

strlen(str) returns "(...) the number of characters in a character array whose first element is pointed to by str up to and not including the first null character". That means, it will count characters until it finds zero.

Check content of strings you pass to strlen() - you may have white characters there (like \r or \n, for example), that were read from the input stream.

Also, an advice - consider using std::string instead of plain char arrays.


Small note: memset() is often optimized for high performance. If this in not your requirement, you can also use std::fill which is a more C++ - like way to fill array of anything:

char testName[arraySize];
std::fill(std::begin(testName), std::end(testName), '\0');

std::begin() (and std::end) works well with arrays of compile-time size.


Also, to answer @SergeyA's comment, I suggest to read this SO post and this answer.

like image 21
Mateusz Grzejek Avatar answered Oct 03 '22 22:10

Mateusz Grzejek