EDIT: I’m sorry for my mistakes in my code snippets, now I see both outputs were same. Below is an edited version.
Let’s say I have a structure:
typedef struct
{
char m[5];
char f[6];
} COUPLE;
And a file containing just phrase RomeoJuliet that I read into an array:
char *data = malloc(11);
FILE *f = fopen("myfile", "rb");
fread(data, 1, 11, f);
fclose(f);
I always use this code when I need to fill my structure from a byte array:
COUPLE titanic;
memcpy(&titanic, data, sizeof(data));
printf("%s and %s", titanic.m, titanic.f);
This works fine, but really my byte array can be very big, so below is my attempt to optimize my code.
COUPLE *titanic = (COUPLE *)data;
printf("%s and %s", titanic->m, titanic->f);
So, my questions are:
- (obsolete) Why do I get different outputs?
- (obsolete) How can I fill a structure just by casting from an array?
- Should I avoid this kind of optimization?
- Are there possible pitfalls in it?
When made my comment to your question, I didn’t have the time to elaborate, so here’s an attempt to answer. The code has changed since, and I’m not sure I would add that comment to the code as it is now.
Nevertheless, the underlying reason that made me add that comment still stands: Unless you measured and found that the code in question does indeed have a significant negative impact on performance, don’t attempt to optimize. Instead, strive to make your code as readable as possible.
I seriously doubt that copying the data in memory will have a significant performance impact after copying them from the disk into memory. However, since your code as provided makes assumptions about the struct’s layout in memory anyway, directly reading into the struct wouldn’t really make the code less readable (or less vulnerable to changes to that layout):
Or, if you indeed have an array, read into the array directly:
Depending on
SIZE, the latter could indeed make a potentially huge difference in performance. Accessing the disk for bigger chunks is, in general, faster that doing it for smaller chunks. (Although disk caching might alleviate that.)