代码是检查在memset中的memset的工作.memset正确初始化数组0但是当我尝试用10初始化它时,它会用一些非常大的垃圾值初始化数组.那有什么问题?
#include <stdio.h>
#include<string.h>
int main(void)
{
int dp[10008],i;
memset(dp,10,sizeof(dp));
for(i=0;i<10;i++)
printf("%d\n",dp[i]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
amd*_*xon 11
男人memset
Run Code Online (Sandbox Code Playgroud)void *memset(void *s, int c, size_t n); DESCRIPTION The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.
你的代码:
memset(dp,10,sizeof(dp));
Run Code Online (Sandbox Code Playgroud)
然后将所有字节初始化dp为10.
所以你的数组看起来像(按字节顺序):
+----------+----------+----------+----------+
| 00001010 | 00001010 | 00001010 | 00001010 | ...
+----------+----------+----------+----------+
Run Code Online (Sandbox Code Playgroud)
如果你把它解释为一个整数你得到(一些大的值).
以上注释基于sizeof int为4仅用于说明目的..
为了满足您初始化所有使用量的需求,请使用:
#include <stdio.h>
#include <string.h>
int main(void)
{
int dp[10008],i;
for(i=0;i<10008;i++)
{
dp[i] = 10;
}
// do other stuff here..
return 0;
}
Run Code Online (Sandbox Code Playgroud)