简体   繁体   中英

Unexpected behaviour of memset()

I am initializing array with 99 in all the elememts

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

but the output I am getting is unexpected.

Output:-

1667457891

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

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

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 memset and fill have different behaviour in this instance, so you must decide which you want: the memset will set each byte to 99, whereas fill will set each element (each int in your case) to 99. If you want an array full of integers that equal 99, use fill as I showed it. If you want each byte set to 99, I would recommend casting the int* to a char* and using fill on that instead of memset , but memset will work for that too.

问题是memset将每个字节设置为99因此第一个int是0x63636363,等于1667457891.使用std::fill代替。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM