How to clear all the elements of array in C?

Your use of strlen() is wrong, that is reliant on the contents of the buffer being a valid string; it doesn’t clear the entire buffer.

Just use memset() with sizeof:

memset(buffer, 0, sizeof buffer);

Note that sizeof is not a function, so no parentheses are needed (or should be used, in my opinion) for cases like these.

If your C library doesn’t include memset(), a plain loop can of course be used:

for(size_t i = 0; i < sizeof buffer; ++i)
  buffer[i] = 0;

If you want to clear just the part that is used, and know that it’s a valid string, your code works of course. I probably wouldn’t have used backwards looping since I find that unintuitive but that’s just me.

Note: if this buffer is for strings, it should be changed to have type char, not uint8_t.

Leave a Comment