c - Is memsetting a element in an array correct? -


is memsetting pointer in array ok or overwriting pointers elements here? better when memset whole memory area or elements in array?

for example:

.... struct pollfd fds[2]; int tmp = 0;  for(; tmp < sizeof(fds[0])/sizeof(fds); tmp ++) {     memset(fds[tmp], 0x00, sizeof(fds[tmp])); } .... 

vs.

.... struct pollfd fds[2];  memset(fds, 0x00, sizeof(fds[tmp])); .... 

you can memset element of array, if want.

still, memsetting consecutive elements 1 call more efficient (the standard guarantees absence of padding between array-elements).

bugs in current code:

  • your first example misses address-of-operator, use:

    memset(&fds[tmp], 0, sizeof *fds); 

    or:

    memset(fds+tmp, 0, sizeof *fds); 
  • your second example passes size of single element instead of whole array, use:

    memset(fds, 0, sizeof fds); 

some side-issues:

  • sizeof operator, no need parentheses unless pass type
  • all-bits-zero not neccessarily same 0 types, though holds modern systems.

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -