Why is memset() incorrectly initializing int?

后端 未结 9 1076
迷失自我
迷失自我 2020-11-28 09:56

Why is the output of the following program 84215045?

int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf(\"%d\", grid         


        
相关标签:
9条回答
  • 2020-11-28 10:34
    memset(grid, 5, 100 * sizeof(int));
    

    You are setting 400 bytes, starting at (char*)grid and ending at (char*)grid + (100 * sizeof(int)), to the value 5 (the casts are necessary here because memset deals in bytes, whereas pointer arithmetic deals in objects.

    84215045 in hex is 0x05050505; since int (on your platform/compiler/etc.) is represented by four bytes, when you print it, you get "four fives."

    0 讨论(0)
  • 2020-11-28 10:37

    This code has been tested. Here is a way to memset an "Integer" array to a value between 0 to 255.

    MinColCost=new unsigned char[(Len+1) * sizeof(int)];
    
    memset(MinColCost,0x5,(Len+1)*sizeof(int));
    
    memset(MinColCost,0xff,(Len+1)*sizeof(int));
    
    0 讨论(0)
  • 2020-11-28 10:41

    memset sets each byte of the destination buffer to the specified value. On your system, an int is four bytes, each of which is 5 after the call to memset. Thus, grid[0] has the value 0x05050505 (hexadecimal), which is 84215045 in decimal.

    Some platforms provide alternative APIs to memset that write wider patterns to the destination buffer; for example, on OS X or iOS, you could use:

    int pattern = 5;
    memset_pattern4(grid, &pattern, sizeof grid);
    

    to get the behavior that you seem to expect. What platform are you targeting?

    In C++, you should just use std::fill_n:

    std::fill_n(grid, 100, 5);
    
    0 讨论(0)
提交回复
热议问题