c - Memcpy or struct assignment? -


i have following code , unsure of whether use structure alignment or memcpy copy struct onto custom "stack" char/byte array.

is there advantageous/disadvantageous following 2 options of code or flat out wrong?

the necessary struct/functions.

struct b {     int type;     struct b *prev; }  struct {     struct b base;     int n;     struct b *another;     char name[1]; /* struct hack */ };  void align(char **ptr, int n) {     intptr_t addr = (intptr_t)*ptr;     if(addr % n != 0) {         addr += n - addr % n;         *ptr = (char *)addr;     } } 

option 1: struct assignment

void struct_assignment() {     char *stack = malloc(400*1000);     char *top_of_stack = stack + 3149; /* example */      struct *var = (struct *)top_of_stack;     align((char **)&var, sizeof(struct b)); /* restrictive alignment member in struct */     var->base.type = 1;     var->base.prev = null;     var->another = (struct base *)var;     char *name = "test";     var->n = strlen(name) + 1;     strcpy(var->name, name);      top_of_stack = (char*)var + sizeof(*var)+ (var->n - 1); /* -1 name[1] */ } 

option 2: memcpy

void memcpying() {     char *stack = malloc(400*1000);     char *top_of_stack = stack + 3149; /* example */      struct var;     var.base.type = 1;     var.base.prev = null;     var.another = null;     char *name = "test";     var.n = strlen(name) + 1;     strcpy(var.name, name);      char *aligned_ptr = top_of_stack;     align(&aligned_ptr, sizeof(struct b)); /* restrictive alignment member in struct */      memcpy(aligned_ptr, &var, sizeof(var) + (var.n - 1); /* -1 name[1] */     struct *var_ptr = (struct a*)aligned_ptr;     var_ptr->another = (struct b *)var_ptr;      top_of_stack = aligned_ptr + sizeof(var)+ (var.n - 1); /* -1 name[1] */ } 

is option 1 struct assignment?

will both options result in same padding , alignment?

will endianness of target architecture affect option 1?

i don't think can called struct assignment. assigning individual fields.

struct assingment in case merely interested in initialization of object on stack "reserving" use temporary:

struct base tmp = {        .type = 1,        .prev = null,        // whatever other fields want initialize }; var->base = tmp; 

or more consise using compound literal:

var->base = (struct base){        .type = 1,        .prev = null,        // whatever other fields want initialize }; 

both methods have advantage of initializing fields might have forgotten 0. copy operation itself, let compiler chose whatever compiler designer saw fit. don't mess around such things unless careful benchmarking tells there real problem.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -