I am a newbie to C still, and I am having a problem with the memset function.
I pass a char * to a function, and inside this function I create an array, and then use memset to set each value. I have been using dbx to watch this variable as it enters the function, and for some reason it gets set to "" after we pass memset.
Firstly, why does this happen? I'm assuming that memset must be resetting the memory where the char * is located?
Secondly, is there a better way to set each element as "0"?
Here is my code:
static char *writeMyStr(char *myStr, int wCount) {
// here myStr is set to "My String is populated"
char **myArr;
myArr = (char **) malloc(sizeof(char *) * wCount);
memset(myArr, 0, sizeof(char *) * wCount); // myStr is set to ""
... populate array ...
}
Are you looking for zero the character, or zero the number? When initializing an array as so:
memset(arr, 0, count);
It is equivalent to
memset(arr, '\0', count);
Because 0=='\0'
. The length of a string is the position of the first null terminator, so your string is zero-length, because the array backing it is filled with zeros. The reason people do this is so that as they add things to the string, they don't need to re-null-terminate it.
If you want your string to be "0000"... use the character zero:
memset(arr, '0', count);
But remember to null-terminate it:
arr[count-1] = '\0';