문제

Here is the code:

#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;
}

I think there is no logic flaw here? But instead of getting a string of 1 printed, I got 16843009.

If I change the memset to std::memset(win, 0, sizeof(win)). Then everything is as expected. The content of win is all zeros.

Am I missing something here?

I'm using g++ 4.7.3 on Ubuntu 13.04.

Sorry for this duplicated question.

Here is the answer. Thanks

Why does "memset(arr, -1, sizeof(arr)/sizeof(int))" not clear an integer array to -1?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top