为什么在这种情况下 memset 会失败?
Why does memset fail in this case?
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
int *b1 = (int *)malloc(sizeof(int)*4);
memset(b1, 0, sizeof(b1));
cout<<"\nArray after memset:";
for(int i=0; i<4; i++)
printf("\t%d", b1[i]);
for(int i=0; i<4; i++)
scanf("%d", &b1[i]);
free(b1);
}
}
输入:
2个
10
20
30
40
10
20
30
40
对于给定的输入,代码给出以下输出:
Array after memset: 0 0 0 0
Array after memset: 0 0 30 40
为什么第二种情况memset会失败?
(另外,我注意到在删除 free(b1) 语句时,memset 工作正常)。
使用
memset(b1, 0, sizeof(int)*4);
因为sizeof(int)*4
是分配内存块的大小。
sizeof(b1)
将 return b1
的大小和存储整数指针的变量。
你想要它指向的东西的大小 - 即 malloc
的参数 - sizeof(int)*4
在 memset
中使用它
还有你为什么在 C++ 代码中使用 scanf
、malloc
。为什么不使用 std::vector
?
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
int *b1 = (int *)malloc(sizeof(int)*4);
memset(b1, 0, sizeof(b1));
cout<<"\nArray after memset:";
for(int i=0; i<4; i++)
printf("\t%d", b1[i]);
for(int i=0; i<4; i++)
scanf("%d", &b1[i]);
free(b1);
}
}
输入: 2个 10 20 30 40 10 20 30 40
对于给定的输入,代码给出以下输出:
Array after memset: 0 0 0 0
Array after memset: 0 0 30 40
为什么第二种情况memset会失败?
(另外,我注意到在删除 free(b1) 语句时,memset 工作正常)。
使用
memset(b1, 0, sizeof(int)*4);
因为sizeof(int)*4
是分配内存块的大小。
sizeof(b1)
将 return b1
的大小和存储整数指针的变量。
你想要它指向的东西的大小 - 即 malloc
的参数 - sizeof(int)*4
在 memset
还有你为什么在 C++ 代码中使用 scanf
、malloc
。为什么不使用 std::vector
?