1

同じタイプの構造が 2 つあり、それらを比較したいと考えています。構造体のサイズは 420 バイトで、最初の 2 バイトは決して一致しないことがわかっているため、比較を行うときにスキップします。次のように memcmp を使用しています。

` typedef struct foo    // total of 420 bytes
{
  char c1,c2 ;
  int x ;
  struct temp y ;
  ...  // lot of other members
  ...
  ...
} ;
foo f1, f2 ;

memset (&f1, 0xff, sizeof(foo) ) ;
memset (&f2,0xff, sizeof(foo) ) ;

update_foo(&f1) ; // function which updates the structure by reading value from flash memory

// Now compare 2 structures starting with value x
if ( memcmp(&f1.x, &f2.x, sizeof(foo)-2 ) == 0 )
  // Do something
else
  // Do something else`

比較の結果、ランダムな値が得られます。「&f1.x」と「&f2.x」を渡すと、最初の 2 バイトがスキップされ、残りの 418 バイトが比較されると仮定します。この仮定は正しいですか?

4

2 に答える 2

1

移植可能な方法でこれを行うのは非常に困難です。異なるプラットフォームの ABI は、各メンバーを単語 len にパディングするか、特定のシナリオでのみパディングする可能性があります。に興味がある...

C はあまり動的な言語ではありません。このようなことを動的に行うことに興味がある場合は、..

typedef struct
{
    int thatCanChange;
    int thatCanChange2;
    int thatICareAbout1;
    ...
    int lastThingICareAbout;
}a;

bool same( a * one, a * two)
{
    return memcmp(&(one->thatICareAbout1), &(two->thatICareAbout1), &(one->lastThingICareAbout) - &(one->thatICareAbout1) + sizeof(one->thatICareAbout1))==0;
}
于 2015-09-22T05:21:51.710 に答える
-1

スキップしたいものが2バイトだけであることが確実な場合は、次を使用できます。

memcmp(((char *)&f1) + 2, ((char *)&f2) + 2, sizeof(foo) - 2);

から比較したい場合はx、次を使用できます。

memcmp(&f1.x, &f2.x, sizeof(foo)-(((char *)&f1.x) - ((char *)&f1)))

したがって、以前のサイズに関係なく機能しxます。

于 2015-09-22T05:16:14.397 に答える