3

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.

kmad1729
  • 1,484
  • 1
  • 16
  • 20
  • 1
    `memset(board, XXX, sizeof(board));` set the value `XXX` for each byte of `board[][]` (maybe 100 bytes). No reasons to think setting each byte (8-bits) will result in each `int` having the value of `INT_MAX`. – chux - Reinstate Monica Jun 13 '16 at 01:41
  • but `man memset` shows the function signature as `void *memset(void *s, int c, size_t n);` So why isn't the second argument int? – kmad1729 Jun 13 '16 at 01:45
  • 1
    @kmad1729 the second argument is `int`, but that value is converted to a byte (`unsigned char` specifically) and the result of that conversion is applied to every byte in the array – M.M Jun 13 '16 at 01:46
  • Reading the documentation (always a good idea when code does not work as expected): `void *memset(void *s, int c, size_t n);` "The memset function copies the value of c (converted to an **unsigned char**) into each of the first n characters of the object pointed to by s." – chux - Reinstate Monica Jun 13 '16 at 01:48
  • 2
    Is this C++? If so, then you could have used `std::fill`: `std::fill(&board[0][0], &board[5][5], INT_MAX);` [See this](http://ideone.com/whq7j1) – PaulMcKenzie Jun 13 '16 at 02:18

1 Answers1

5

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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148