关于用memcmp()比较两个结构体,做了以下调试: 代码
#include<stdio.h>
#include<stdlib.h> #include<string.h> struct CmpTest { char a; short b; int c; }; int main() { CmpTest t1, t2; printf("%d\t",memcmp(&t1, &t2, sizeof(CmpTest))); CmpTest t3, t4; memset(&t3, 0, sizeof(CmpTest)); memset(&t4, 0, sizeof(CmpTest)); printf("%d\n",memcmp(&t3, &t4, sizeof(CmpTest))); t1.a = 'a'; t1.b = 1; t1.c = 123456; t2.a = 'a'; t2.b = 1; t2.c = 123456; printf("%d\t",memcmp(&t1, &t2, sizeof(CmpTest))); t3.a = 'a'; t3.b = 1; t3.c = 123456; t4.a = 'a'; t4.b = 1; t4.c = 123456; printf("%d\n",memcmp(&t3, &t4, sizeof(CmpTest))); t2 = t1; printf("%d\t",memcmp(&t1, &t2, sizeof(CmpTest))); t4 = t3; printf("%d\n",memcmp(&t3, &t4, sizeof(CmpTest))); } 输出结果为: 1 0 0 0 如果把结构体改成: struct CmpTest
{ char a; short b; int c; char d; }; 输出结果为: 1 0 1 0 0 0 由此得出结论: 可以通过memcmp()来比较2个相同的结构体变量,但这2个变量必须在赋值前进行清零初始化(否则结果不准确) ,或者2者是通过直接对等赋值而来。 另外,结构体的命名对memcmp()没有影响(只要内部结构完全一样)。因为: 代码3
#include<stdio.h>
#include<stdlib.h> #include<string.h> struct CmpTest { char a; short b; int c; char d; }; struct CmpTest1 { char a; short b; int c; char d; }; int main() { CmpTest t1; CmpTest1 t2; printf("%d\t",memcmp(&t1, &t2, sizeof(CmpTest))); CmpTest t3; CmpTest1 t4; memset(&t3, 0, sizeof(CmpTest)); memset(&t4, 0, sizeof(CmpTest)); printf("%d\n",memcmp(&t3, &t4, sizeof(CmpTest))); t1.a = 'a'; t1.b = 1; t1.c = 123456; t1.d = 'a'; t2.a = 'a'; t2.b = 1; t2.c = 123456; t2.d = 'a'; printf("%d\t",memcmp(&t1, &t2, sizeof(CmpTest))); t3.a = 'a'; t3.b = 1; t3.c = 123456; t3.d = 'a'; t4.a = 'a'; t4.b = 1; t4.c = 123456; t4.d = 'a'; printf("%d\n",memcmp(&t3, &t4, sizeof(CmpTest))); } 输出结果为: 1 0 1 0 |
|