I am trying to initialize a 2d array with some integer.If I initialize the array to 0 I am getting 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
}
C++ Note: We can use memset() to set all values as 0 or -1 for integral data types also. It will not work if we use it to set as other values.
memset() is used to fill a block of memory with a particular value. The syntax of memset() function is as follows : // ptr ==> Starting address of memory to be filled // x ==> Value to be filled // n ==> Number of bytes to be filled starting // from ptr to be filled void *memset(void *ptr, int x, size_t n);
memset allows you to fill individual bytes as memory and you are trying to set integer values (maybe 4 or more bytes.) Your approach will only work on the number 0 and -1 as these are both represented in binary as 00000000 or 11111111 .
It depends. But, for sure memset is faster or equal to the for-loop. If you are uncertain of your environment or too lazy to test, take the safe route and go with memset. Please specify which one you mean by "above."
memset
set every byte of your array to 1
not every int
element.
Use an initializer list with all values set to 1 or a loop statement to copy a value of 1
to all the elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With