c - Swap pointers instead of memcpy -


edit : I'm sorry for your mistakes in my code snippets, now I have both outputs I was the only one to see. Below is an edited version.

Let me assume that I have a structure:

  typedef struct {char m [5]; Four f [6]; } Couple;   

and a single file containing the RomeoJuliet that I read in an array:

  char * data = malloc (11); FILE * f = fopen ("myfile", "rb"); Fred (data, 1, 11, f); Fclose (f);   

When I need to fill my structure with a byte array, then I always use this code:

  coupical titanic; Memcpy (& Titanic, data, sizeof (data)); Printf ("% s and% s", titanic.m, titanic.f);   

It works fine, but in fact my byte array can be very large, so here's my attempt to customize my code below.

  COUPLE * titanic = (COUPLE *) data; Printf ("% s and% s", Titanic-> gt, titanic-> f);   

So, my questions are:

  1. (obsolete) Why do I get different outputs?
  2. (obsolete) How can I fill out a composition by simply casting from an array?
  3. Should I avoid such adaptation?
  4. Is there possibly harm?

    You commented on your question, I did not have time to expand, So here is an attempt to answer. Since the code has changed, and I am not sure that I will add that comment to that code because it is now

    However, the underlying reason is that I still want to add this comment Stands: Unless you measured and found that the code in question is really important, negative impact on the display, Do not try to optimize < / Em> Instead, make your code as far as possible Try it

    I suspect that by copying the data into the memory, they will have an important display effect after copying them from memory to disk. However, since the provided code has any assumptions about the layout of the structure in memory, reading directly into the string will not actually make the code readable (or less insecure to change in that layout): < / P>

      Cool Titanic; FILE * f = fopen ("myfile", "rb"); Fred (and Titanic, Size (Titanic), 1, F);   

    Or, if you have an array, read directly in the array:

      Quill Titanic [SIZE]; FILE * f = fopen ("myfile", "rb"); Fred (and Tatanic, Size (Titanic), Size, F); Depending on   

    , later could actually make potentially huge differences in performance. By reaching the disk for large amounts, in general, it is faster for this small part (though disk caching may be less.)

Comments