rezaulhsagar's blog

By rezaulhsagar, history, 8 years ago, In English

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!

  • Vote: I like it
  • -1
  • Vote: I do not like it

»
8 years ago, # |
Rev. 2   Vote: I like it -26 Vote: I do not like it

You can use memset, but in a different way

memset (a, large_value, sizeof(a[0][0]) * size_arr * size_arr);
»
8 years ago, # |
  Vote: I like it +10 Vote: I do not like it

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.

»
8 years ago, # |
  Vote: I like it +16 Vote: I do not like it

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)).

»
8 years ago, # |
  Vote: I like it +18 Vote: I do not like it
fill(&grid[0][0], &grid[0][0] + (maxx + 7) * (maxx + 7), large_value);
»
8 years ago, # |
  Vote: I like it +3 Vote: I do not like it

Why not make 2139062143 or other memsetable value your infinity?