本文介绍了为多类型结构避免memset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想避免在这样的结构上使用memset():

I would like to avoid using memset() on a structure like this:

typedef struct {
    int size;
    float param1;
} StructA;

typedef struct {
    StructA a;
    unsigned int state;
    float param2;
} Object;

我可以做这样的事情(伪代码,我现在无法检查)吗?

Can I do something like this (pseudo code, I can't check right now)?

Object obj;
int *adr = (int*)&obj;
for (int i; i < sizeof(obj); i++) {
    *adr++ = 0;
}

它将obj的每个成员设置为零吗?

Will it set every member of obj to zero?

编辑:回答有关评论的问题.我一直在研究某些情况(具有uni型结构),其中memset的速度是手动初始化 的两倍.因此,我也将考虑尝试初始化多类型结构.

EDIT: to answer questions on comments.I have been working on some cases (with uni-type structures), where memset is twice as slow than initializing by hand. So I will consider trying initializing multi-type structure as well.

避免memcpy()也会很好(避免使用<string.h> lib).

Avoiding memcpy() would be nice too (avoiding the <string.h> lib).

推荐答案

通用零初始化器将所有内容(递归地)初始化为适当类型的零.

The universal zero initializer initializes everything (recursively) to zero of the proper type.

Object object = {0};

这篇关于为多类型结构避免memset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 19:22