C语言 Memset 将数组元素设置为 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18523548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Memset to set array elements to 0
提问by P R
I'm a newbie playing with memset and pointers.
我是一个玩 memset 和指针的新手。
When I compile and run :
当我编译并运行时:
main(){
int a;
int *b = (int *)malloc(5*sizeof(int));
memset(b,0, 5*sizeof(int));
if (b != NULL){
for(a=0;a<4;a++){
//b[a] = a*a;
printf
("Value of b %u\n", b[a]);
}
}
free(b);
b = NULL;
}
I am able to print all elements value as 0. However when I change the memset line to
我能够将所有元素值打印为 0。但是当我将 memset 行更改为
memset(b,0, sizeof(b));
I always get one of the elements with a huge number which I assumed to be the address of that element. However on trying to print both address and value at element with:
我总是得到一个具有巨大数字的元素,我认为它是该元素的地址。但是,在尝试使用以下元素打印地址和值时:
printf("Value of b %u and address %u\n", b[a], b+(a*sizeof(int)));
I get two long numbers which aren't the same.
我得到两个不相同的长数字。
What exactly is happening? Have I used memset in the wrong way? Please tell me if I need to attach screenshots of output/ clarify my question.
究竟发生了什么?我是否以错误的方式使用了 memset?请告诉我是否需要附上输出截图/澄清我的问题。
Thanks!
谢谢!
回答by Barmar
bis a pointer, so sizeof(b)is the size of a pointer, most likely 4 or 8 on current systems. So you're only setting the first few bytes to 0, instead of the entire array.
b是一个指针,指针sizeof(b)的大小也是如此,在当前系统上很可能是 4 或 8。所以你只是将前几个字节设置为 0,而不是整个数组。
If you had declared bas an array, e.g.
如果您已声明b为数组,例如
int b[5];
then sizeof(b)would be the size of the entire array, and your memsetwould work as you expected.
那么sizeof(b)将是整个数组的大小,您memset将按预期工作。

