0

这是代码:

#include <iostream>
#include <cstring>

int main()
{
    int win[11];
    std::memset(win, 1, sizeof(win));
    for (int i = 0; i < 11; ++i)
        std::cout << win[i] << ' ';
    std::cout << std::endl;

    return 0;
}

我认为这里没有逻辑缺陷?但我没有得到一串1打印出来,而是得到了16843009.

如果我更改memsetstd::memset(win, 0, sizeof(win)). 然后一切都如预期的那样。win的内容全为零。

我在这里错过了什么吗?

我正在g++ 4.7.3使用Ubuntu 13.04.

很抱歉这个重复的问题。

这是答案。谢谢

为什么“memset(arr, -1, sizeof(arr)/sizeof(int))”不能将整数数组清除为-1?

4

2 回答 2

9

ints are usually four bytes long. But memset sets the value of individual bytes, so you're setting each value to 0x01010101, which just so happens to equal 16843009.

于 2013-10-11T22:04:48.487 回答
3

The memset function writes over memory without understanding its structure in any way. If you write a bunch of random 1's all over an accounting report, will that make the report show that the company has spent $1? I don't think so. Maybe it will show 111111 dollars. Maybe not. Who knows.

To modify an object's value intelligently, you have to understand its structure. The memset function does not understand the structure of win and just scribbles 1 all over its bytes. What that means, memset does not know or care.

于 2013-10-11T22:07:06.317 回答