[英]Using memset to set an array
I am a newbie to C still, and I am having a problem with the memset function. 我仍然是C的新手,我遇到了memset功能的问题。
I pass a char * to a function, and inside this function I create an array, and then use memset to set each value. 我将一个char *传递给一个函数,在这个函数中我创建一个数组,然后使用memset来设置每个值。 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. 我一直在使用dbx来观察这个变量,因为它进入函数,并且由于某种原因它在我们传递memset后被设置为“”。
Firstly, why does this happen? 首先,为什么会发生这种情况? I'm assuming that memset must be resetting the memory where the char * is located? 我假设memset必须重置char *所在的内存?
Secondly, is there a better way to set each element as "0"? 其次,有没有更好的方法将每个元素设置为“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'
. 因为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. 人们这样做的原因是,当他们向字符串添加内容时,他们不需要重新使用null来终止它。
If you want your string to be "0000"... use the character zero: 如果你想让你的字符串为“0000”...使用字符零:
memset(arr, '0', count);
But remember to null-terminate it: 但请记住以null结尾:
arr[count-1] = '\0';
If you're trying to zero-fill the array initially, it is better use calloc rather than malloc. 如果您最初尝试对数组进行零填充,则最好使用calloc而不是malloc。
All malloc does it give you a block of memory with random, indeterminate values. 所有malloc都会为您提供一个具有随机,不确定值的内存块。 Whereas calloc gives you a block of memory and zero-fills it, guaranteeing that you won't have junk in there. 而calloc给你一块内存并将其填充为零,保证你不会有垃圾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.