Hi, In a graph problem, I need to memset a whole 2D array with a large value that denotes INFINITY.
Currently, I am doing this by running a O(N*N) loop.
const int maxx = something;
int grid[maxx+7][maxx+7];
for(int i=0;i<maxx;i++){
for(int j=0;j<maxx;j++){
grid[i][j] = large_value;
}
}
Is there a better way to do this?
Also, I have tried memset
function.
memset(grid,127,sizeof grid)
resets all values to 2139062143
memset(grid,128,sizeof grid)
resets all values to -2139062144
Why memset works like this?
Thanks in advance!
You can use memset, but in a different way
What's the difference?
memset is to manipulate bytes. A byte is 8 bits, and the binary of 127 is 1111111(28 - 1), so memset(127) is to make all bytes of the array be 01111111. A int is 4 bytes, so the manipulation can make the element of this array be 01111111011111110111111101111111, which is just 2139062143. Sorry for my poor English.
memset
works byte by byte and not 'element' by 'element' (in your case int).There is no way (in C++) of setting all values in a 2D-array to some constant (unless you write your own function(s)).
Why not make
2139062143
or other memsetable value your infinity?