3
votes

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 ... 

}
2
Those people are idiots. The return value of malloc is a void *. You can't do anything with it without casting it, either implicitly or explicitly.Charlie Martin
@CharlieMartin This is C, not C++. In C++ you need to cast.Mysticial
@CharlieMartin: Or perhaps those people just know C.Kerrek SB
@Blood: Unless you need to call malloc, because you have to interact with C code, for example.rodrigo
@Mystical in C, if you don't cast it lint will (properly) complain. It's actually possible in C for pointers to have different sizes and for an uncast assignment to lose things.Charlie Martin

2 Answers

11
votes

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';
2
votes

If you're trying to zero-fill the array initially, it is better use calloc rather than malloc.

All malloc does it give you a block of memory with random, indeterminate values. Whereas calloc gives you a block of memory and zero-fills it, guaranteeing that you won't have junk in there.