Benjamin Benjamin - 3 months ago 29
C Question

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, "");


It depends on what you mean by "empty". If you just want a zero-length string, then your example will work.

This will also work:

buffer[0] = '\0';

If you want to zero the entire contents of the string, you can do it this way:


but this will only work for zeroing up to the first NULL character.

If the string is a static array, you can use: