[c] Proper way to empty a C-String

I've been working on a project in C that requires me to mess around with strings a lot. Normally, I do program in C++, so this is a bit different than just saying string.empty().

I'm wondering what would be the proper way to empty a string in C. Would this be it?

buffer[80] = "Hello World!\n";

// ...

strcpy(buffer, "");

This question is related to c string strcpy

The answer is


Depends on what you mean by emptying. If you just want an empty string, you could do

buffer[0] = 0;

If you want to set every element to zero, do

memset(buffer, 0, 80);

Two other ways are strcpy(str, ""); and string[0] = 0

To really delete the Variable contents (in case you have dirty code which is not working properly with the snippets above :P ) use a loop like in the example below.

#include <string.h>

...

int i=0;
for(i=0;i<strlen(string);i++)
{
    string[i] = 0;
}

In case you want to clear a dynamic allocated array of chars from the beginning, you may either use a combination of malloc() and memset() or - and this is way faster - calloc() which does the same thing as malloc but initializing the whole array with Null.

At last i want you to have your runtime in mind. All the way more, if you're handling huge arrays (6 digits and above) you should try to set the first value to Null instead of running memset() through the whole String.

It may look dirtier at first, but is way faster. You just need to pay more attention on your code ;)

I hope this was useful for anybody ;)


I'm a beginner but...Up to my knowledge,the best way is

strncpy(dest_string,"",strlen(dest_string));

needs name of string and its length will zero all characters other methods might stop at the first zero they encounter

    void strClear(char p[],u8 len){u8 i=0; 
        if(len){while(i<len){p[i]=0;i++;}}
    }

If you are trying to clear out a receive buffer for something that receives strings I have found the best way is to use memset as described above. The reason is that no matter how big the next received string is (limited to sizeof buffer of course), it will automatically be an asciiz string if written into a buffer that has been pre-zeroed.