结构体数据检验问题
现在接收到一个结构体类型的数据,结构体成员宽度不一。需要校验接收到的和本地数据是否一致,而且是每个成员数据是否一致,请问除了一一比较,还有其他方法吗?
[解决办法]
如果肯定没有字节对齐和大小端问题的话,可以用memcpy函数。
[解决办法]
纠正上帖:
如果肯定没有字节对齐和大小端问题的话,可以用memcmp函数。
memcmp
Compare characters in two buffers.
int memcmp( const void *buf1, const void *buf2, size_t count );
Routine Required Header Compatibility
memcmp <memory.h> or <string.h> ANSI, Win 95, Win NT
For additional compatibility information, see Compatibility in the Introduction.
Libraries
LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version
Return Value
The return value indicates the relationship between the buffers.
Return Value Relationship of First count Bytes of buf1 and buf2
< 0 buf1 less than buf2
0 buf1 identical to buf2
> 0 buf1 greater than buf2
Parameters
buf1
First buffer
buf2
Second buffer
count
Number of characters
Remarks
The memcmp function compares the first count bytes of buf1 and buf2 and returns a value indicating their relationship.
Example
/* MEMCMP.C: This program uses memcmp to compare
* the strings named first and second. If the first
* 19 bytes of the strings are equal, the program
* considers the strings to be equal.
*/
#include <string.h>
#include <stdio.h>
void main( void )
{
char first[] = "12345678901234567890";
char second[] = "12345678901234567891";
int result;
printf( "Compare '%.19s' to '%.19s':\n", first, second );
result = memcmp( first, second, 19 );
if( result < 0 )
printf( "First is less than second.\n" );
else if( result == 0 )
printf( "First is equal to second.\n" );
else if( result > 0 )
printf( "First is greater than second.\n" );
printf( "Compare '%.20s' to '%.20s':\n", first, second );
result = memcmp( first, second, 20 );
if( result < 0 )
printf( "First is less than second.\n" );
else if( result == 0 )
printf( "First is equal to second.\n" );
else if( result > 0 )
printf( "First is greater than second.\n" );
}
Output
Compare '1234567890123456789' to '1234567890123456789':
First is equal to second.
Compare '12345678901234567890' to '12345678901234567891':
First is less than second.
Buffer Manipulation Routines
See Also _memccpy, memchr, memcpy, memset, strcmp, strncmp
[解决办法]
如果肯定没有
◆字节对齐不一致
◆字节对齐虽然一致,但为对齐填充的字节值不一致
◆大小端不一致
问题的话,可以用memcmp函数。
[解决办法]
判断数据是否一致!最后一一比较会比较靠谱
[解决办法]
如果结构体不大,直接比较就行了。如果是很长的数据,为了性能,直接按总线长度取数据一一比较。
[解决办法]
只能一一比较的。按二进制方式整个的比较是不行的
成员之间可能有空缺,而这些空缺的字节不一致的话,如果成员都一致,仍然应该认为两个结构体是相等的。但是二进制方式比较的话就会输出不相等的结论
[解决办法]
如果你真的怕到处写类似的代码一一比较成员的麻烦,可以在结构体中重载 == 和 != 操作符,这样在需要比较的地方像普通变量那样直接写比较表达式就可以了