का उपयोग कर सी में structs की तुलना करें मुझे पता है कि memcmp()
का उपयोग उन संरचनाओं की तुलना करने के लिए नहीं किया जा सकता है जो memset()
0 से 0 प्रारंभिक पैडिंग के कारण नहीं हैं। हालांकि, मेरे कार्यक्रम में मेरे पास शुरुआत में कुछ अलग-अलग प्रकार के साथ एक संरचना है, फिर संरचना के अंत तक एक ही प्रकार के कई दर्जन हैं। मेरा विचार था कि पहले कुछ प्रकारों की मैन्युअल रूप से तुलना करें, फिर उसी टाइप किए गए सदस्यों के शेष संगत मेमोरी ब्लॉक पर memcmp()
का उपयोग करें।memcmp() और पॉइंटर अंकगणित
मेरा सवाल है, संरचना मानक पैडिंग के बारे में सी मानक गारंटी क्या है? क्या मैं किसी भी या सभी कंपाइलरों पर भरोसेमंद इसे प्राप्त कर सकता हूं? क्या सी मानक समान प्रकार के सदस्यों के बीच स्ट्रक्चर पैडिंग डालने की अनुमति देता है?
रूप gcc
साथ इरादा मैं अपने प्रस्तावित समाधान को लागू किया है, और यह वास्तव में काम करने के लिए लगता है:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct foo
{
char a;
void *b;
int c;
int d;
int e;
int f;
};
static void create_struct(struct foo *p)
{
p->a = 'a';
p->b = NULL;
p->c = 1;
p->d = 2;
p->e = 3;
p->f = 4;
}
static int compare(struct foo *p1, struct foo *p2)
{
if (p1->a != p2->a)
return 1;
if (p1->b != p2->b)
return 1;
return
/* Note the typecasts to char * so we don't get a size in ints. */
memcmp(
/* A pointer to the start of the same type members. */
&(p1->c),
&(p2->c),
/* A pointer to the start of the last element to be compared. */
(char *)&(p2->f)
/* Plus its size to compare until the end of the last element. */
+sizeof(p2->f)
/* Minus the first element, so only c..f are compared. */
-(char *)&(p2->c)
) != 0;
}
int main(int argc, char **argv)
{
struct foo *p1, *p2;
int ret;
/* The loop is to ensure there isn't a fluke with uninitialized padding
* being the same.
*/
do
{
p1 = malloc(sizeof(struct foo));
p2 = malloc(sizeof(struct foo));
create_struct(p1);
create_struct(p2);
ret = compare(p1, p2);
free(p1);
free(p2);
if (ret)
puts("no match");
else
puts("match");
}
while (!ret);
return 0;
}
माइनर: चूंकि आपकी पॉइंटर तुलना 0 या 1 लौट रही है, इसलिए 'memcmp() '' memcmp()! = 0' के साथ' memcmp() '0 या 1 को बीमा करने का सुझाव दिया गया है। – chux
@chux अच्छा विचार, सुझाव के लिए धन्यवाद। – John