memset to INT_MAX in C++ [duplicate]

老子叫甜甜 提交于 2019-12-19 11:44:16

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/37780779/memset-to-int-max-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!