Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to empty a char array?

Tags:

arrays

c

char

Have an array of chars like char members[255]. How can I empty it completely without using a loop?

char members[255]; 

By "empty" I mean that if it had some values stored in it then it should not. For example if I do strcat then old value should not remain

members = "old value";  //empty it efficiently strcat(members,"new"); // should return only new and not "old value new" 
like image 409
Alex Xander Avatar asked Oct 13 '09 10:10

Alex Xander


People also ask

How do you empty an array of characters?

Use the memset Function to Clear Char Array in Ch> header file. memset takes three arguments - the first is the void pointer to the memory region, the second argument is the constant byte value, and the last one denotes the number of bytes to be filled at the given memory address.

How do you empty a char?

To create an empty char, we either can assign it a null value \0 or default Unicode value \u0000 . The \u0000 is a default value for char used by the Java compiler at the time of object creation. In Java, like other primitives, a char has to have a value.

How do you initialize a char array to be empty?

Another useful method to initialize a char array is to assign a string value in the declaration statement. The string literal should have fewer characters than the length of the array; otherwise, there will be only part of the string stored and no terminating null character at the end of the buffer.


2 Answers

using

  memset(members, 0, 255); 

in general

  memset(members, 0, sizeof members); 

if the array is in scope, or

  memset(members, 0, nMembers * (sizeof members[0]) ); 

if you only have the pointer value, and nMembers is the number of elements in the array.


EDIT Of course, now the requirement has changed from the generic task of clearing an array to purely resetting a string, memset is overkill and just zeroing the first element suffices (as noted in other answers).


EDIT In order to use memset, you have to include string.h.

like image 74
Steve Gilham Avatar answered Oct 23 '22 20:10

Steve Gilham


Depends on what you mean by 'empty':

members[0] = '\0'; 
like image 37
Felix Avatar answered Oct 23 '22 20:10

Felix