memset,0,1,-1和初始化int型数组

memset : fill memory with a constant byte

函数定义: 

       #include <string.h>

       void *memset(void *s, int c, size_t n);

        The  memset()  function  fills  the  first  n  bytes of the memory area pointed to by s with the constant byte c.

#include <stdio.h>
#include <string.h>

#define ARRIASIZE	5

int main()
{
	int buf[ARRIASIZE];
	int i;
	printf("sizeof(buf) is %d\n", sizeof(buf));
	for (i = 0; i < ARRIASIZE; i++)
		printf("buf[%d] = %d\n", i, buf[i]);
	printf("first\r\n");
	memset(buf, 0x1, ARRIASIZE);
	for (i = 0; i < ARRIASIZE; i++)
		printf("buf[%d] = %d\n", i, buf[i]);

	printf("second\r\n");
	memset(buf, 0x1, sizeof(buf));
	for (i = 0; i < ARRIASIZE; i++)
		printf("buf[%d] = %d\n", i, buf[i]);

	printf("third\r\n");
	memset(buf, 0x0, ARRIASIZE);
	for (i = 0; i < ARRIASIZE; i++)
		printf("buf[%d] = %d\n", i, buf[i]);

	printf("fourth\r\n");
	memset(buf, 0x0, sizeof(buf));
	for (i = 0; i < ARRIASIZE; i++)
		printf("buf[%d] = %d\n", i, buf[i]);
	return 0;
}

memset实现供参考:

void *memSet(void *s, int c, size_t n)
{
	if (NULL == s || n < 0)
		return NULL;
	char * tmpS = (char *)s;
	while(n-- > 0)
		*tmpS++ = c;
		return s; 
}

如果在对int型数组进行初始化时,我们仍可以进行一些特殊的初始化
如:

初始化数组元素都为0
初始化数组元素都为-1

原因:
由于int类型占4byte,即32bit
0的二进制形式表示为0000 0000 0000 0000 0000 0000 0000 0000
-1的二进制形式表示为1111 1111 1111 1111 1111 1111 1111 1111
在使用memset时,将用value的最低位的1byte(8bit)来填充内存块,即用1111 1111来填充。所以数组中每个元素的二进制表示形式还是1111 1111 1111 1111 1111 1111 1111 1111。0的情况同理。
 

初始化为1
使用memset
1的二进制形式为0000 0000 0000 0000 0000 0000 0000 0001
在使用memset时,将用最低位的1bye(8bit)来填充内存块,即用0000 0001来填充。所以数组中每个元素的二进制形式就表示位0000 0001 0000 0001 0000 0001 0000 0001。十进制形式位16843009

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值