【问题标题】:Why does memset fail in this case?为什么 memset 在这种情况下会失败?
【发布时间】: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


    【解决方案1】:

    使用

    memset(b1, 0, sizeof(int)*4);
    

    sizeof(int)*4 是分配的内存块的大小。

    【讨论】:

      【解决方案2】:

      sizeof(b1) 将返回b1 的大小和存储整数指针的变量。

      你想要它指向的东西的大小 - 即malloc的参数 - sizeof(int)*4

      memset中使用它

      还有你为什么在 C++ 代码中使用scanfmalloc。为什么不使用std::vector

      【讨论】:

      • 混合coutprintf 也不是一个好主意。缓冲让一个人感到困惑
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 2014-05-31
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多