Memset array up to 1

I am trying to initialize a 2d array with some integer.If I initialize the array to 0, I get the correct results, but if I use some other integer, I get some random values.

int main() { int array[4][4]; memset(array,1,sizeof(int)*16); printf("%d",array[1][2]); <---- Not set to 1 } 
+6
source share
3 answers

memset set every byte of your array 1 not every int element.

Use a list of initializers with all values ​​set to 1 or a loop statement to copy the value 1 to all elements.

+10
source

memset only works bytes. Zeroing bits works in general, because all integer zeros tend to have zero bits, so grouping four bytes with a zero bit into one zero bit int still gives you zero. However, for things that are not bytes, the easiest way to initialize them is only to explicitly initialize them all.

+4
source

memset allows you to fill in individual bytes as memory, and you are trying to set integer values ​​(maybe 4 or more bytes). Your approach will only work with numbers 0 and -1 , since they are both represented in binary format as 00000000 or 11111111 .

The for loop doesn't bother too much:

 int main() { int i, val = 1, max = 4; int array[max][max]; max = max * max; for(i = 0 i < max; i++) { array[i] = val; } } 
+2
source

All Articles