简体   繁体   English

在c中使用memset()

[英]Usage of memset() in c

I have written a small program to get used to memset() operation: 我编写了一个小程序来习惯memset()操作:

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

int main()
{
    int arr[10], i;
    int t = INT_MAX;
    memset(arr, t, sizeof(arr));
    for (i = 0; i < 10; i++)
        printf("%d\t",arr[i]);

    printf("%d",t);
    return 0;
}

The result of the above program is: 上述计划的结果是:

-1 -1 -1 -1 -1 -1 -1 -1 -1 -1

2147483647

What is the behaviour of the memset() in the above program? memset()在上面的程序中的行为是什么? Why is it setting the array elements to -1 ? 为什么将数组元素设置为-1

memset only takes the lower eight bits of the value and fills the whole buffer with these bits. memset仅占用该值的低8位,并用这些位填充整个缓冲区。 The lower eight bits of MAX_INT are all ones ( 0xFF ), and thus the array is afterwards filled with all ones. MAX_INT的低8位全为1( 0xFF ),因此数组之后填充所有1。 For signed integers, this is -1. 对于有符号整数,这是-1。

Memset sets the first sizeof(arr) bytes of the block of memory pointed by arr to t interpreted as an unsigned char. Memset将arr指向的内存块的第一个sizeof(arr)字节设置为解释为unsigned char。 So what u get when you read out ints from arr depends in the interpretation of those bytes on your platform. 因此,当您从arr读取整数时,您获得的内容取决于您平台上这些字节的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM