Unexpected behavior of memset ()

I initialize an array with 99 in all elements

#include<iostream> #include<cstring> int main(){ int a[10]; memset(a,99,10); std::cout<<a[0]<<std::endl; return 0; } 

but the conclusion that I get is unexpected.

Output: -

1667457891

What is the reason for the abnormal behavior of this memset function.

+4
source share
2 answers

Firstly, a memset takes a size in bytes, not the number of elements in an array, because it cannot know how large each element is. You need to use sizeof to get the size in bytes of the array and instead specify memset :

 memset(a, 99, sizeof(a)); 

However, in C ++, prefer std::fill because it is type safe, more flexible, and can sometimes be more efficient:

 std::fill(begin(a), end(a), 99); 

The second and more pressing problem is that in this case memset and fill have different behavior, so you have to decide what you want: memset will set each byte to 99, while fill will set each element (each int in your case ) to 99. If you need an array full of integers equal to 99, use fill , as I showed. If you want each byte to be set to 99, I would recommend using int* in char* and using fill memset instead, but memset will work too.

+11
source

The problem is that memset sets each byte to 99 , so the first int is 0x63636363, which is 1667457891. Instead, use std::fill .

+1
source

Source: https://habr.com/ru/post/1442511/


All Articles