How I can clear a string before of use ?

How I can clear a string.

For example aux [10] is my string

In the first loot I used aux[0] = 1 aux[1] = 1 aux[2] = 1 aux[3] = 1

but if I went printf all aux [10] was now 111

After this, I aux[0] = 2 aux[1] = 2 aux[2] = 2.

but if I went printf all aux [10] now, didn't was 222, but 2221.

How I can clear a string before of use ?
C strings are terminated by the character value zero '\0'. So you must set the last character to '\0':
1
2
3
4
5
char aux[10];
aux[0] = '2';
aux[1] = '2';
aux[2] = '2';
aux[3] = '\0'; // end of c-string marker 
Certainly my ask didn't was about this. I want know how after to use a string, clean her.
It is difficult to understand. Can you ask your question again?

What is 'aux'? Is it a char array?
When your string type is actually an array of char, you mark the end of the string with the number 0. So, you can "clear" the string by setting all the char to zero.
If you want to live dangerously you can just set the first character position to 0. e.g. string[0] = 0

If you want to live life on the safe side you can use strcpy(string, "");

1
2
3
4
char *lTemp = new char[1024];
lTemp[0] = 0; OR strcpy(lTemp, "");
// do stuff
delete lTemp;

or

1
2
char lTemp[1024];
lTemp[0] = 0; OR strcpy(lTemp, "");



If you want to live dangerously you can just set the first character position to 0


That's not really living dangerously. That's kind of all you need to do.

If you want to live life on the safe side you can use strcpy(string, "");


That does the exact same thing as setting the first character to 0.
If you just set the first char in the string to 0, you also have to remember to null terminate the string when you set the other chars (as Galik said above)

Andy

P.S. Yet another way to zero an array variable!

memset(lTemp, 0, sizeof(lTemp);

With an array allocated with new you should use

char *pTemp = new char[1024]();

The trailing () tells the compiler to zero all the elements.

To re-zero the whole array, use memset, but with the array size (here, 1024) and not sizeof(pTemp) !

P.P.S. To initialize an array to zero (all element), you can use any of

1
2
3
 char a1[16] = "";
 char a2[16] = {0};
 char a3[16] = {'\0'};


The rule for aggregate init is that if you init any but not all members/elements, the rest are zeroed. If you init none, it is just left alone. So zeroing the first elem is enough to zero all elems.

With VC, empty braces also works (= {};). But I don't know if that is standard behaviour.

(Out of habit I use the first form if the buffer is to contain a null terminated string; the second if it's to be treated as individual chars. )
Last edited on
Topic archived. No new replies allowed.