111

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"
6
  • 3
    What do you mean "empty an array"? Commented Oct 13, 2009 at 10:53
  • 6
    members[0]=members[1]=members[2]=members[3]...=members[255]=0 no loop there ;) Commented Oct 13, 2009 at 11:18
  • 22
    So your "array" is a special kind of array: it is a string. To "empty" a string, set it's first element to '\0': members[0] = '\0'; Commented Oct 13, 2009 at 11:27
  • Community seems to be in favour of memset. But is that most efficient way given my requirements? Commented Oct 13, 2009 at 11:48
  • 2
    @Alex Xander: "Community" is clearly wrong in this case. There are situations that call for 'memset' (like wiping out data to prevent unauthorized use), but for the simple string reset (as in your case) the correct answer is to zero the first element only. Commented Oct 13, 2009 at 14:11

13 Answers 13

211

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 - I would go for this as it ensures that all array elements are in a known state.
It goes against the (epic) requirement of not using a loop, though.
While memset is probably not implemented as a recursion, it could be -- in either case, the iteration is decently hidden from sight, which was the ostensible requirement.
43

Depends on what you mean by 'empty':

members[0] = '\0';

8 Comments

That would only change the value of members[0], not members[1] through members[254]. Fine if you are accessing sequentially...but not so fine in other cases.
After the OP's edit it seems my solution should work for his requirements, as strcat() will find the NULL byte and treat it accordingly.
Not a better solution. Just a solution to a different problem.
There's no way to "empty" an abstract array in C. Every array constains something, even if it is zeroes. The notion of "emptying an array" is only applicable to higher-level logical interpretations of array contents. For example, the contents of the array might be interpreted as a C-string. In that case the proper way to "empty" it is to set the very first element to '\0'. Exactly what Felix did. I don't know what other interpretations the OP might have in mind, but without making it more specific all those attempts with 'memset' are just meaningless answers to a meaningless question.
@tinkertim: There's no NULL here. And no, 'strcat' does not know how to handle NULL. It will crash if you pass NULL to it.
|
13

Don't bother trying to zero-out your char array if you are dealing with strings. Below is a simple way to work with the char strings.

Copy (assign new string):

strcpy(members, "hello");

Concatenate (add the string):

strcat(members, " world");

Empty string:

members[0] = 0;

Simple like that.

Comments

8

char members[255] = {0};

2 Comments

Nope, because he didn't specify that it must be done after initializing. Especially this may have been understood by his first example before edit and because it's also very common use case to clear an array.
I give you +2 as compensation that he gave you -1 :P :D
6

EDIT: Given the most recent edit to the question, this will no longer work as there is no null termination - if you tried to print the array, you would get your characters followed by a number of non-human-readable characters. However, I'm leaving this answer here as community wiki for posterity.

char members[255] = { 0 };

That should work. According to the C Programming Language:

If the array has fixed size, the number of initializers may not exceed the number of members of the array; if there are fewer, the remaining members are initialized with 0.

This means that every element of the array will have a value of 0. I'm not sure if that is what you would consider "empty" or not, since 0 is a valid value for a char.

1 Comment

It depends on how you define "empty". The char with a value of 0 is not a human-readable character and the array of chars is in a known state. I would consider that empty. It also does the exact same thing as memset (if my recollection of memset is correct - it's been too long since I've used C).
4

You cannot empty an array as such, it always contains the same amount of data.

In a bigger context the data in the array may represent an empty list of items, but that has to be defined in addition to the array. The most common ways to do this is to keep a count of valid items (see the answer by pmg) or for strings to terminate them with a zero character (the answer by Felix). There are also more complicated ways, for example a ring buffer uses two indices for the positions where data is added and removed.

Comments

4

Use bzero(array name, no.of bytes to be cleared);

Comments

3
members[0] = 0;

is enough, given your requirements.

Notice however this is not "emptying" the buffer. The memory is still allocated, valid character values may still exist in it, and so forth..

2 Comments

Can be also written as *members = 0;
Even 0 is a valid character. We do not know if members are treated as C string or not.
2

I'd go with

members_in_use = 0;

6 Comments

It actually makes a lot of sense, since the OP is asking for an operation (emptying) that is not part of a C array - therefore, ideally, he'd implement a new data structure, and pmg's way of signaling the structure is empty is good enough.
No, it really doesn't make any sense.
Kinopiko: Apparently you don't understand the approach then
Kinopiko: read starblue answer as it explains my reasoning better than I can explain in a comment (thank you starblue)
Hmm, this is an interesting approach, will members_in_use still be an array? Can I later do a; member_in_use[5] = value? Is this equivalent to memset(members_in_use, 0, 255); as Steve stated? If so, why use one instead of the other?
|
1

By "empty an array" if you mean reset to 0, then you can use bzero.

#include <strings.h>  
void bzero(void *s, size_t n);  

If you want to fill the array with some other default character then you may use memset function.

#include <string.h>  
void *memset(void *s, int c, size_t n);  

1 Comment

bzero and memset (usually) both use a loop.
1

In this case just members[0] = 0 works.

Comments

0

Disclaimer: I don't usually program in C so there may be any syntax gotcha in my examples, but I hope the ideas I try to express are clear.

If "emptying" means "containing an empty string", you can just assign the first array item to zero, which will effectively make the array to contain an empry string:

members[0] = 0;

If "emptying" means "freeing the memory it is using", you should not use a fixed char array in the first place. Rather, you should define a pointer to char, and then do malloc / free (or string assignment) as appropriate.

An example using only static strings:

char* emptyString="";
char* members;

//Set string value
members = "old value";

//Empty string value
member = emptyString

//Will return just "new"
strcat(members,"new");

Comments

0

You can use the following instruction:

strcpy_s(members, "");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.