How to clear all the elements of array in C?

volatile static uint8_t buffer[16]; void ResetBuffer(){ for(int i=strlen((char*)buffer);i>=0;i--) buffer[i]='\0'; } 

The buffer variable must be always used in micro controller, so I've used volatile static and it's global variable. But, to make all the buffer clear, is it right to code like this? If it's wrong or there's any other simple code, please show me some simple code.

I've heard that if I want to make it clear, then it would be easier to just make the first element empty. like this : buffer[0] = '\0'; But, when I code it like that, another elements are still remained.

I know it's a very simple question. But I'm confused. I've been normally programming in C++ or Java, so it's quite confused for me to program in C.

2

3 Answers

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.

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

Assigning '\0' 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)); 
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like