用memset在C整数数组 [英] Using memset for integer array in c

查看:180
本文介绍了用memset在C整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 字符海峡[] =美丽的地球;
memset的(STR,'*',6);
的printf(%S,STR);输出:
****** FUL地球

1)像上面的memset使用下面??给出,我们可以初始化只有少数整数数组索引值1

  INT改编[15];
memset的(ARR,1,6);


解决方案

没有,你不能使用 memset的()这样。该手册页说(重点煤矿):


  

memset的()函数填充第一个 N 字节的内存区指向取值随着不断的字节 C


由于一个 INT 通常是4或8个字节,这将不会削减它。


如果你(的错误!! 的)尝试做到这一点:

  INT改编[15];
memset的(ARR,1,6 *的sizeof(INT)); //错误!

那么第6 INT 在数组中实际上将被设置为0x01010101 = 16843009。

这是有史以来真正接受的写在一个非字节的数据类型(S)数据的斑点唯一的一次,是 memset的(事,0,sizeof的(事)); 零出全struture /阵列。这工作,因为NULL,00000000,0.0,都是完全为零。


解决方案是使用循环,并自己设置的:

  INT改编[15];
INT I;对于(I = 0; I&10 6 ++ⅰ)//设置数组中的前6个元件
    改编由[i] = 1; //为值1。

char str[]="beautiful earth";
memset(str,'*',6);
printf("%s",str);

output:
******ful earth

1) Like above use of memset, can we initialize only few integer array index values to 1 as given below??

int arr[15];
memset(arr,1,6);

解决方案

No, you cannot use memset() like this. The manpage says (emphasis mine):

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

Since an int is usually 4 or 8 bytes, this won't cut it.


If you (incorrectly!!) try to do this:

int arr[15];
memset(arr, 1, 6*sizeof(int));    //wrong!

then the first 6 ints in the array will actually be set to 0x01010101 = 16843009.

The only time it's ever really acceptable to write over a "blob" of data with non-byte datatype(s), is memset(thing, 0, sizeof(thing)); to "zero-out" the whole struture/array. This works because NULL, 0x00000000, 0.0, are all completely zeros.


The solution is to use a for loop and set it yourself:

int arr[15];
int i;

for (i=0; i<6; ++i)    // Set the first 6 elements in the array
    arr[i] = 1;        // to the value 1.

这篇关于用memset在C整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆