How to empty char array

I ran into this problem while coding today.
<<<<<<<<<<<<<<<<<<<Start of Code>>>>>>>>>>>>>>>>>
//Test1
char test[] = "naBac a";
str_compare="nABAc A";
compare_strings(test,str_compare);

//Test2
test = "aaa";
str_compare = "AAA";
compare_strings(test,str_compare);

<<<<<<<<<<<<<<End of Code>>>>>>>>>>>>>>>>>>>

I got some errors, basically I had to clear out the char array before reassigning and proceeding with 2nd test case.
I tried 2 ways to do the same
1) test[]="";
2) test[0]={0};
Neither of them worked.

This brought me to the interesting question, how to clear a character array, to reassign it and use.
you can't assign sting literals to arrays at any time other than initialization. IE:

1
2
char test[] = "lsdfjsld";
test = "ljd";  // ERROR 


instead, you must COPY the string to the array. This is typically done with the strcpy function

1
2
char test[] = "old";
strcpy(test,"new");  // OK 


but note that you have to be careful not to overflow the buffer!

1
2
char test[] = "four";  // only large enough for 4 characters
strcpy(test,"explode");  // compiles OK, but VERY VERY BAD, your program will explode 

You could use memset here is a link to it.
http://www.cplusplus.com/reference/clibrary/cstring/memset/

So you could do something like this.
memset(test,'0',sizeof(test));

That should set your array to all 0, or is that not what you want?

clearing a string before you replace it with a new string is a waste of time.

That's like doing this:

1
2
3
4
5
6
int C = a;  // first set to 'a'
cout << C;

C = 0;  // then clear it
C = b;  // then to 'b'
cout << C;


What's the point of clearing 'C' there? None. You're already replacing it with the line below, no need to clear it first.

Same thing with a string.
Topic archived. No new replies allowed.