-
clearing an char array
how would i reset an char temp [30] array back to empty
for instance, after a loop it has some string stored in it. i want to clear it.
i could do it manually by going through a loop and setting each of its elements to 0 ascii
but too annoying. is there like a built in function for that.
thanks :)
-
You can just call a handy function named "memset" which sets a specified memory range to a specified value. It works as follows.
Code:
char array[30];
// ... some computations...
// Now we clear our array
memset( array, 0, sizeof(array) );
Param 1: Pointer to destination
Param 2: Character to set
Param 3: Number of characters
NOTE: There are a few things to note here. An array acts like a pointer so we don't need to have the address-of operator before the name.
Here is another quick example to zero out the memory of a structure Foo..
Code:
Foo myStruct;
memset( &myStruct, 0, sizeof(Foo) );
It is located in the either one of these headers
memory.h
string.h
Also if you are using windows.h they have a handy macro named "ZeroMemory" which simply takes the first and third parameter of memset.
-
oh thats right
memset, i forgot about it :D
well, is there a string related function?
-
>>Here is another quick example to zero out the memory of a structure Foo..
Be careful doing that one, if the struct contains pointers or floats they could get messed up. This is covered here .
-
Quote:
Originally posted by Hammer
>>Here is another quick example to zero out the memory of a structure Foo..
Be careful doing that one, if the struct contains pointers or floats they could get messed up. This is covered here .
yup, i agree with that
-
If you don't want to empty the complete char array, you can do this:
myarray[0] = '\0';
to give to impression that the array has been emptied.
It depends on what you want to do...
-
nah, i want to empty it completely cuz i am going through a loop to keep reading names from a file and i dont wanna use up space
so i wanna re use the char array
i was hoping that there might be some C++ function which could do it