Why is memset() incorrectly initializing int?

后端 未结 9 1127
迷失自我
迷失自我 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."

提交回复
热议问题