I created a boolean 2D array and used memset
like this :
bool chk[3][3];
memset(chk, 1, 9*sizeof(chk[0]));
I got output as expected using the following blocks of code (got 1 in every row )
for(int i = 0 ; i < 3; i++){
for(int j = 0; j < 3; j++)
cout<<chk[i][j] <<" ";
cout<<endl;
}
but when I tried to manipulate the array I got unexpected result
and then I tried with
memset(chk, 1, 9*sizeof(chk[0][0]));
and this time everything was fine and got my expected result(after manipulation)
Can you please help me pointing out what exactly happened in memset() ?
The memset
call in your first code snippet has three problems:
The size calculation is incorrect. Instead of 9*sizeof(chk[0])
you could use 3*sizeof(chk[0])
. But really you should just use sizeof(chk)
, because you have a local variable, not a pointer, as you would have with a formal argument.
The assumption that memory representation of true
is bitpattern 1, is not guaranteed by the standard. In practice it will hold, but it would be far better to use the value true
directly instead of a needless assumption.
In C++ simply zero-initialize the variable to make it all zeroes, e.g. bool chk[3][3] = {};
, or use std::fill
to fill an array with a given value, e.g. fill( &chk[0][0], &chk[0][0] + 9, true );
.
Addendum: to be pedantic, in point 1 there is an assumption that a bool
is 1 byte. That's also an assumption that holds in practice but is not guaranteed by the standard. Happily it's not an issue for use of std::fill
.