119

I thought by setting the first element to a null would clear the entire contents of a char array.

char my_custom_data[40] = "Hello!";
my_custom_data[0] = '\0';

However, this only sets the first element to null.

or

my_custom_data[0] = 0; 

rather than use memset, I thought the 2 examples above should clear all the data.

3
  • 1
    Jared, why did you set the c++ tag? he talked about "C" and did not add any C++ related tags. Commented Mar 11, 2009 at 1:08
  • 2
    This applies equally well to character arrays in C++, even though he didn't specify. Commented Mar 11, 2009 at 5:37
  • 4
    I've removed the C++ tag to avoid what we've already seen with people offering C++ specific solutions Commented Mar 11, 2009 at 16:34

16 Answers 16

129

It depends on how you want to view the array. If you are viewing the array as a series of chars, then the only way to clear out the data is to touch every entry. memset is probably the most effective way to achieve this.

On the other hand, if you are choosing to view this as a C/C++ null terminated string, setting the first byte to 0 will effectively clear the string.

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

9 Comments

They key word in the answer is 'effectively'. Only the first element is begin set to 0 and the rest still have undefined values but if you are treating the array as a null terminated string and the first element is null, then the string is considered empty.
indeed, this is the answer folks.
@caparcode, exactly. That's why it's very important to understand how the array is being used.
Yes, that is what I should have said in my first post. The char is a terminated string. so either these will do that trick. char[0] = '\0'; or char[0] = 0. I am not sure but I heard that using '\0' is better for using null terminated strings.
@robUK, yes you are correct. Technically '\0' is equal to 0 (in ascii) but you should use '\0' because it makes your intention clear
|
85

An array in C is just a memory location, so indeed, your my_custom_data[0] = '\0'; assignment simply sets the first element to zero and leaves the other elements intact.

If you want to clear all the elements of the array, you'll have to visit each element. That is what memset is for:

memset(&arr[0], 0, sizeof(arr));

This is generally the fastest way to take care of this. If you can use C++, consider std::fill instead:

char *begin = &arr;
char *end = begin + sizeof(arr);
std::fill(begin, end, 0);

10 Comments

I believe the second version should be: std::fill( arr, arr+ sizeof(arr)/sizeof(arr[0]), 0 );
Clarification: don't use sizeof with fill because you'll get in trouble later with arrays of int, long, double or what have you.
I prefer: std::fill(&arr[0], &arr[arr_len], 0);
Zan Lynx, that's undefined behavior. you cannot do &arr[arr_len]. but you have to do std::fill(arr, arr + sizeof arr, 0); or if you have the length somewhere std::fill(arr, arr + arr_len, 0); assuming an array of char
It is valid only in C . although the question clearly targetted C (another guy added a C++ tag, i've no clue why), the std::fill shows C++ affinity :)
|
27

Why would you think setting a single element would clear the entire array? In C, especially, little ever happens without the programmer explicitly programming it. If you set the first element to zero (or any value), then you have done exactly that, and nothing more.

When initializing you can set an array to zero:

char mcd[40] = {0}; /* sets the whole array */

Otherwise, I don't know any technique other than memset, or something similar.

5 Comments

I guess this depends on the compiler you use
@cocoafan: No, it is not compiler dependent. It is part of the language specification. Any compiler that behaves differently is not following the C language.
I didn't know that, thank you. I couldn't find any resource where I can read this special case. Would be nice to have it as a bookmark.
It is called partial initialization. I don't have the C99 spec, but here are two sources: bit.ly/enBC2m "You do not need to initialize all elements in an array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type." bit.ly/f9asHH "If there are fewer initializers than elements in the array, the remaining elements are automatically initialized to 0"
This does not apply to an array that has already been declared and assigned values does it?
12

Use:

memset(my_custom_data, 0, sizeof(my_custom_data));

Or:

memset(my_custom_data, 0, strlen(my_custom_data));

2 Comments

The second option (memset(my_custom_data, 0, strlen(my_custom_data));) will only clear out to the first '\0', which could be beyond the end of the array. This may, or may not, be okay.
The first option worked fine on an ESP32, after I tried a lot of other things.
10

Try the following code:

void clean(char *var) {
    int i = 0;
    while(var[i] != '\0') {
        var[i] = '\0';
        i++;
    }
}

2 Comments

FYI - indent code by 4 spaces or select it and hit the 'code' button, which looks like two lines of binary.
Excellent solution if you don't wanna include string.h for memset().
7

Why not use memset()? That's how to do it.

Setting the first element leaves the rest of the memory untouched, but str functions will treat the data as empty.

2 Comments

Don't use memset over readability: stackoverflow.com/questions/453432/…
and what is your answer then?
6

Pls find below where I have explained with data in the array after case 1 & case 2.

char sc_ArrData[ 100 ];
strcpy(sc_ArrData,"Hai" );

Case 1:

sc_ArrData[0] = '\0';

Result:

-   "sc_ArrData"
[0] 0 ''
[1] 97 'a'
[2] 105 'i'
[3] 0 ''

Case 2:

memset(&sc_ArrData[0], 0, sizeof(sc_ArrData));

Result:

-   "sc_ArrData"
[0] 0 ''
[1] 0 ''
[2] 0 ''
[3] 0 ''

Though setting first argument to NULL will do the trick, using memset is advisable

Comments

5

I usually just do like this:

memset(bufferar, '\0', sizeof(bufferar));

Comments

4

Nope. All you are doing is setting the first value to '\0' or 0.

If you are working with null terminated strings, then in the first example, you'll get behavior that mimics what you expect, however the memory is still set.

If you want to clear the memory without using memset, use a for loop.

3 Comments

I say no on the for loop. Try not to write your own "improved" (and usually not) library functions. In fact, memset and memcpy are rather special are often inlined into custom machine code for the CPU based on what is known about data alignment and length.
@Zan the OP doesn't want to use memset (perhaps he's embedded and doesn't have it available). But yes, memset is usually highly optimal, and likely faster than a for loop.
True, however he didn't want to use memset, so I suggested a for loop.
2

You should use memset. Setting just the first element won't work, you need to set all elements - if not, how could you set only the first element to 0?

1 Comment

memset shouldn't be used over readability: stackoverflow.com/questions/453432/…
2

Writing a null character to the first character does just that. If you treat it as a string, code obeying the null termination character will treat it as a null string, but that is not the same as clearing the data. If you want to actually clear the data you'll need to use memset.

Comments

1

I thought by setting the first element to a null would clear the entire contents of a char array.

That is not correct as you discovered

However, this only sets the first element to null.

Exactly!

You need to use memset to clear all the data, it is not sufficient to set one of the entries to null.

However, if setting an element of the array to null means something special (for example when using a null terminating string in) it might be sufficient to set the first element to null. That way any user of the array will understand that it is empty even though the array still includes the old chars in memory

1 Comment

Don't use "memset" over readability: stackoverflow.com/questions/453432/…
1

set the first element to NULL. printing the char array will give you nothing back.

Comments

1

How about the following:

bzero(my_custom_data,40);

Comments

-3
void clearArray (char *input[]){
    *input = ' '; 
}

1 Comment

This is not CLEARING, it is just setting first character to ' '! I think you wanted to write *input = '\0'
-4

Try the following:

strcpy(my_custom_data,"");

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.