简体   繁体   English

Memset枚举数组值设置不正确(C / C ++)

[英]Memset enum array values not setting correctly (C/C++)

I'm trying to use memset to set all values in an enum array to a single value, but I'm not seeing the correct results. 我正在尝试使用memset将枚举数组中的所有值设置为单个值,但我没有看到正确的结果。 The first memset works, the second does not. 第一个memset工作,第二个没有。 My code: 我的代码:

// definitions
#define NUM_THREADS     1

enum ThreadState
{
    INITIALIZING,
    READY_TO_CALCULATE,
    CALCULATED,
    READY_TO_UPDATE,
    UPDATED
};


// Later on, in the code...
ThreadState Thread_States[NUM_THREADS];

// Somehow this works - after this statement, every entry in Thread_States is INITIALIZING
memset(Thread_States, INITIALIZING, NUM_THREADS* sizeof(ThreadState));

// ... later on (or even immediately right after) ...

// Failure - after this statement, every entry in Thread_States is 16843009
memset(Thread_States, READY_TO_CALCULATE, NUM_THREADS* sizeof(ThreadState));

As explained in the comments, the first time I call memset, the values are set to what I expect (INITIALIZING, ie, 0). 正如评论中所解释的那样,我第一次调用memset时,值被设置为我期望的值(INITIALIZING,即0)。 When I run the second statement, I don't see the values set to READY_TO_CALCULATE (ie, 1). 当我运行第二个语句时,我看不到将值设置为READY_TO_CALCULATE(即1)。 Rather, they're set to 16843009, when I check the debugger. 相反,当我检查调试器时,它们被设置为16843009。

Is there a reason this relatively simple use of memset is inconsistent in its behavior? 有没有理由相对简单地使用memset的行为不一致?

Thank you. 谢谢。

The memset function sets each byte of the memory to the second argument (after the second argument is truncated). memset函数将内存的每个字节设置为第二个参数(在第二个参数被截断之后)。 As enumerations are (normally) the size of int you will get the wrong result. 由于枚举(通常)是int的大小,您将得到错误的结果。 The only time it will work is for an enumeration value of zero, as it will then set all bytes to zero. 它唯一有效的时间是枚举值为零,因为它会将所有字节设置为零。

If you use eg READY_TO_CALCULATE you will set each byte to 1 , which will create int values of 0x01010101 instead of 0x00000001 . 如果使用例如READY_TO_CALCULATE ,则将每个字节设置为1 ,这将创建int0x01010101而不是0x00000001

Is your question C or C++? 你的问题是C还是C ++?

In case of C, remember to loop over the array to set each value, as memset is just not meant for this kind of function. 在C的情况下,记住循环遍历数组以设置每个值,因为memset不适用于此类函数。 You're trying to set elements, not memory. 你试图设置元素,而不是内存。

In case of C++, use an enum class for the state. 对于C ++,请使用枚举类作为状态。 Also, try to encapsulate your thread state in its own class that manages it, and make the default initializer construct it properly. 此外,尝试将线程状态封装在自己的管理它的类中,并使默认初始化程序正确构造它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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