c++ memset

最近一直在做动态规划有关的问题,并且经常性的需要把dp数组置为0,就经常性的用memset(dp,0,sizeof(dp))这么写。。直到今天。
今天遇到了一道题 需要把dp数组初始化为1,我就像往常一样写了memset(dp,1,sizeof(dp)),但是整体代码写完后怎么都不对 然后输出一看一串奇怪的数字16843009。。

1
2
3
4
5
6
7
8
9
10
#include<bits/stdc++.h>
using namespace std;

int main() {
int a[10];
memset(a,1,sizeof(a));
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
return 0;
}

what happened?
首先要知道memset在哪,在string.h头文件里面。
memset是按字节赋值,int4字节,memset(dp,1,sizeof(dp))这句话的意思就是把每个int型的dp的每个字节都赋值为00000001,那么每个int型dp元素的值为:
00000001 00000001 00000001 00000001,转换成十进制就是16843009。那为什么赋值0或者-1没错?
因为0的补码是00000000,-1的补码是11111111,再翻译回去还是0和-1。所以除了0和-1赋值的话可以用fill。
比如fill(a,a+n,1)这样就可以把数组a的每一个元素的值都赋值为1了。