Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c - How do I compare two members of an array of structures?

I have a doubt about comparing two members of an array of structures. I have my function which receives the indices of two different structures and compares them. Finally, after all fields have been checked, the function must return an integer indicating similarity.

I made this code:

int compareRecord(RecordSoggetto soggetto1, RecordSoggetto soggetto2) {
    int similiarity = 0;
    if (strcmp(soggetto1.name, soggetto2.name) == 0)
        similiarity += 7;
    if (strcmp(soggetto1.surname, soggetto2.surname) == 0)
        return similiarity += 7;
}

I call the function in this way:

printf("
Insert first index");
scanf("%d", &first);
printf("
Insert second index");
scanf("%d", &second);
similiarity = confrontaRecord(???);
printf("
Similiarity= %d%%", similiarity);

But now I don't know what parameters I have to enter when I call the function, also I'm not sure if the parameters inside the function itself are correct This is the structure:

 typedef struct {
     char name[DIM_NOME];
     char surname[DIM_COGNOME];
 } RecordSoggetto;

 RecordSoggetto soggetto[DIM_RECORD];

Can you help me?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your compare function has undefined behaviour. It does not return a value in every path. Change it like this:

int compareRecord(RecordSoggetto soggetto1, RecordSoggetto soggetto2){
  int similiarity=0;
  if (strcmp(soggetto1.name, soggetto2.name) == 0)
    similiarity+=7;
  if (strcmp(soggetto1.surname, soggetto2.surname) == 0)
    similiarity+=7;
  return similiarity;
}

Regarding the call:

similiarity = confrontaRecord(soggetto[first], soggetto[second]);

If you don't want to copy the full structs, you can also only pass their address, which results in better performance (less memory being copied). Please note that in this case I added const so that compareRecord can't modify the RecordSoggettos. That helps prevent bugs.

int compareRecord(const RecordSoggetto* soggetto1, const RecordSoggetto* soggetto2){
  int similiarity=0;
  if (strcmp(soggetto1->name, soggetto2->name) == 0)
    similiarity+=7;
  if (strcmp(soggetto1->surname, soggetto2->surname) == 0)
    similiarity+=7;
  return similiarity;
}

similiarity = confrontaRecord(&soggetto[first], &soggetto[second]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...