Avoid memset for multi-type structure

I would like to avoid using memset()in such a structure:

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;
}

Will it set each obj element to zero?

EDIT : answer questions about comments. I worked on some cases (with structures of the same type), where it memsetis twice as slow as manual initialization. Therefore, I will consider the possibility of initializing a multi-type structure.

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

-1
source share
5 answers

() .

Object object = {0};
+5

"" , . , , memset(), .

const Object zeroobject = {0};

/* ... */
Object obj;
memcpy(&obj, &zeroobject, sizeof obj);
/* assignment may work too */
obj = zeroobject;
+1

memset . 0 IEEE- , C- . param1 param2 0.0.

, :

Object obj = { 0 };
+1

.

memset:

memset(&obj, 0, sizeof(obj));

, , :

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

memset, . , . , .


, . sizeof . int char.

, , - .

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

, , . 8 /64 , .

-3
source

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


All Articles