I have tried variations using sizeof() with unreliable results. This method works, but is it bogus? Can it be improved? I am not worried about it being portable.
// -- Unit Variables -- struct { // Complex Structure // Lots of nested arrays, // integer values, etc. } message; char replyBuffer[20]; // Input Buffer // Return size of message structure unsigned int getMessageSize(void) { int i, *p1, *p2; p1 = (int *)&message; // Create pointer to Message Struct p2 = (int *)&replyBuffer; // Create pointer to replyBuffer i = p2-p1; // Calculate message structure size return(i); // Does this really work? }
I have tried variations using sizeof() with unreliable results. You'll want to go into more detail on that one. What made you qualify the results of sizeof() as "unreliable"? The method you showed is quite certainly a lot less reliable than just using sizeof().
Thank you all for the quick response. The sizeof results were larger than the actual size. When I used the sizeof results to load new data into the message structure, it would wipe out the replyBuffer. I am not real keen on using pack(1) because I do not want to slow down the functions that access the message structure. How is this 'very dangerous' and 'a lot less reliable' when it seems to be working? After the build the pointers are not going to change, are they? I am not arguing, just curious. Since the consensus seems to be that my method is bogus, I will experiment some more with sizeof.
The sizeof results were larger than the actual size. When I used the sizeof results to load new data into the message structure, it would wipe out the replyBuffer. That means either you "used the sizeof results" in some incorrect way, or you found an enormous compiler bug. You'll have to forgive people if they think the former is a good deal more likely. Whichever it is, the next step is the same: you really should show an example case that actually exhibits the problem.