一、memset函数原型:
void memset ( void *s , char ch, unsigned n )
函数功能:将s为首地址的一片连续的n个字节内存单元都赋值为ch
二、使用memset函数
# include <stdio.h>
# include <string.h>
int main() {
char c[10];
// 把数组c的10个元素都赋值为'a'
memset(c, 'a', 10);
for (int i=0; i<10; i++) {
printf("%c\t", c[i]);
}
return 0;
}
输出:
a a a a a a a a a a
# include <stdio.h>
# include <string.h>
int main()
{
int a[10];
memset(a, 0, 10*sizeof(int));
/* 数组a是int类型的,一个int占4个字节,所以a[10]实际上有40个字节。
而char类型只占1个字节,所以不需要乘sizeof(char) */
// 输出数组a和b
for (int i=0; i<10; i++) {
printf("%d\t", a[i]);
}
printf("\n");
return 0;
}
输出:
0 0 0 0 0 0 0 0 0 0
emset函数是对n个字节进行赋值。而char类型占1个字节。但是int类型占4个字节,所以对int、short等类型赋值时,需要乘上字节数。
三、给int类型赋值为1
# include <stdio.h>
# include <string.h>
int main()
{
int a[10];
memset(a, 1, 10*sizeof(int));
// 输出数组a
for (int i=0; i<10; i++) {
printf("%d\t", a[i]);
}
return 0;
}
输出:
16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009
输出结果可以看到,并没有给数组元素赋值为1。为什么呢?这是为什么呢?
前面我们说过,memset是对连续的n个字节进行赋值。但是int类型占4个字节。memset赋值时,直接将数组拆成40个字节赋值,并没有把4个字节看成一个整体
大型站长资讯类网站! https://www.0518zz.cn