Search code examples
c++cmemset

memset to INT_MAX in C++


I have the following code:

int board[5][5];

memset(board, INT_MAX, sizeof(board));
//printing out INT_MAX
cout << INT_MAX << endl;

for(int r = 0; r < 5; r++) {
        for(int c = 0; c < 5; c++) {
            cout << setw(3) << board[r][c];
        }   
        cout << endl;
}

For some reason i am getting all -1s in my array:

2147483647
 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1

How can I explain? Why aren't all the elements setting to INT_MAX? When I print INT_MAX it is printed out fine.


Solution

  • The second parameter to memset() is a single byte. memset() does not fill the specified area of memory with ints, but with single bytes.

    If you want to initialize your board array of ints, you'll have to do it with the same kind of a loop that your test program uses to print its contents.