【发布时间】:2016-02-14 03:28:33
【问题描述】:
#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
对于给定的输入,代码给出以下输出:
memset 后的数组:0 0 0 0
memset 后的数组:0 0 30 40
为什么memset在第二种情况下会失败?
(另外,我注意到删除 free(b1) 语句后,memset 可以正常工作)。
【问题讨论】:
标签: c++ dynamic-memory-allocation memset