Memset不起作用 [英] Memset not working
问题描述
我正在尝试通过以下代码在纯2D阵列上使用memset:
#include< iostream>
#include< cstring>
使用命名空间std;
int main()
{
int l [3] [3];
memset(l,1,sizeof(l)); (int i = 0; i< 3; i ++)的
{(int j = 0; j< 3; j ++){
cout<< l [i] [j]< ;
}
cout<<恩德尔
}
返回0;
}
我希望使用以下行将整个数组初始化为1:
内存集(l,1,sizeof(l));
但是我没有得到期望值,它给了我以下输出:
16843009 16843009 16843009
16843009 16843009 16843009
16843009 16843009 16843009
认为这可能是编译器问题,所以我尝试使用Ideone:
memset
适用于字节,因此它可以填充您的字节具有0x01010101值的int数组(假定int为32位),该数组为十进制16843009。
int l [3] [3];
std :: fill_n(* l,sizeof l / sizeof ** l,1);
* l
在这里衰减 int [3] [3]
指向指向数组第一个元素的指针( int *
), sizeof l / sizeof ** l
产生数组元素的数量。
它使用C ++的要求,数组必须在内存中连续放置没有间隙,因此多维数组具有与一维数组相同的布局。例如。 int [3] [3]
与 int [3 * 3]
具有相同的布局。
并且与 memset
不同, std :: fill_n
在对象级别进行操作,不在字节上。对于内置类型,优化版本通常按SIMD指令内联,效率不低于 memset
。
I am trying to use memset on a pure 2D Array, using the following piece of code :
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int l[3][3];
memset (l, 1, sizeof(l));
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << l[i][j] << " ";
}
cout << endl;
}
return 0;
}
I want the whole array to be initialized by 1 using the line :
memset (l, 1, sizeof(l));
But I don't get the expected value, it gives me the following output:
16843009 16843009 16843009
16843009 16843009 16843009
16843009 16843009 16843009
Thought it might be a compiler problem, so I tried using Ideone:
Please help.
memset
works on bytes, so it fills your array of ints with 0x01010101 values (assuming int is 32 bits) which is decimal 16843009.
If you need to fill a 2-dimensional C-style array with a number:
int l[3][3];
std::fill_n(*l, sizeof l / sizeof **l, 1);
*l
here decays int[3][3]
into a pointer to the first element of the array (int*
), sizeof l / sizeof **l
yields the count of array elements.
It uses the C++ requirement that arrays be laid out contiguously in memory with no gaps, so that multi-dimensional arrays have the same layout as single-dimensional ones. E.g. int [3][3]
has the same layout as int[3 * 3]
.
And, unlike memset
, std::fill_n
operates on object level, not on bytes. For built-in types the optimized version normally inlines as SIMD instructions, not less efficient than memset
.
这篇关于Memset不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!