How to clear all the elements of array in C?

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 doesnt 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 doesnt 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 its a valid string, your code works of course. I probably wouldnt have used backwards looping since I find that unintuitive but thats just me.

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

memset(buffer, 0, sizeof(buffer));

How to clear all the elements of array in C?

Assigning to the first element to the character array is enough to make it an empty string but it does not clear the entire array.

In order to clear you need to use

memset(buffer, 0, sizeof(buffer));

or

bzero(buffer, sizeof(buffer));

Leave a Reply

Your email address will not be published.