Why is the output of the following program 84215045
?
int grid[110]; int main() { memset(grid, 5, 100 * sizeof(int)); printf("%d", grid[0]); return 0; }
memset predates (by quite a bit) the addition of function prototypes to C. Without a prototype, you can't pass a char to a function -- when/if you try, it'll be promoted to int when you pass it, and what the function receives is an int .
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 . Show activity on this post. Because memset works on byte and set every byte to 1.
The memset() function sets the first count bytes of dest to the value c. The value of c is converted to an unsigned character.
memset can be faster since it is written in assembler, whereas std::fill is a template function which simply does a loop internally.
memset
sets each byte of the destination buffer to the specified value. On your system, an int
is four bytes, each of which is 5 after the call to memset
. Thus, grid[0]
has the value 0x05050505
(hexadecimal), which is 84215045
in decimal.
Some platforms provide alternative APIs to memset
that write wider patterns to the destination buffer; for example, on OS X or iOS, you could use:
int pattern = 5; memset_pattern4(grid, &pattern, sizeof grid);
to get the behavior that you seem to expect. What platform are you targeting?
In C++, you should just use std::fill_n
:
std::fill_n(grid, 100, 5);
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