[英]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
對於給定的輸入,代碼給出以下輸出:
memset之后的數組:0 0 0 0
memset之后的數組:0 0 30 40
為什么memset在第二種情況下失敗?
(此外,我注意到在刪除free(b1)語句時,memset可以正常工作)。
采用
memset(b1, 0, sizeof(int)*4);
因為sizeof(int)*4
是分配的內存塊的大小。
sizeof(b1)
將返回的尺寸b1
和可變存儲的整數指針。
您需要它所指向的對象的大小-即malloc
的參數sizeof(int)*4
在memset
使用它
另外,為什么還要在C ++代碼中使用scanf
和malloc
。 為什么不使用std::vector
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.