C:比较结构中的两个字符串

C: comparing two strings from a struct

我几乎是 C 的新手,想知道如何比较来自两个单独的结构成员变量的字符串。也许提供我的代码会使我的要求更加清晰。

我有以下结构:

typedef struct mentry {
     char *surname;
     int house_number;
     char *postcode;
     char *full_address;
} MEntry;

我想比较两个单独的 MEntry 变量。我想检查两个条目的姓氏是否相同。所以,我写了下面的方法:

 int me_compare(MEntry *me1, MEntry *me2) 
 {

     int surnameResult;


     char me1Surname = *(me1->surname);
     char me2Surname = *(me2->surname);

     surnameResult = strcmp(me1Surname, me2Surname);
     return surnameResult;
}

当我编译我的程序时,我收到以下消息:

 mentry.c:30:6: warning: passing argument 1 of ‘strcmp’ makes pointer from integer without a cast [enabled by default]
  surnameResult = strcmp(me1Surname, me2Surname);

我是不是认为这条线是错误的:

 char me1Surname = *(me1->surname);

将 me1Surname 设置为姓氏值而不是姓氏地址?

我还收到另一个警告:

"In file included from mentry.c:2:0:
 /usr/include/string.h:140:12:note: expected ‘const char *’ but argument  is of type ‘char’
extern int strcmp (const char *__s1, const char *__s2)"

谁能解释为什么会出现这个警告?

你太努力了:

尝试显而易见的方法:

int me_compare(const MEntry *me1, const MEntry *me2) 
{
  return strcmp(me1->surname, me2->surname);
}

您可以试试这个简单的例子。只需要制作两个 MEntry 结构对象来测试它,并通过使用它们的地址来比较结构中的指针姓氏。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char *surname;
    int house_number;
    char *postcode;
    char *full_address;
} MEntry;

int me_compare(MEntry *me1, MEntry *me2);

int
main(void) {
    MEntry me1 = {"McLeod", 27, "3432", "27 Baker Street, London"};
    MEntry me2 = {"Baggins", 19, "3242", "145 Bag End, Shire"};

    if (me_compare(&me1, &me2) == 0) {
        printf("Surnames are identical.\n");
    } else {
        printf("Surnames are different.\n");
    }

    return 0;
}

int 
me_compare(MEntry *me1, MEntry *me2) {
    int surnameResult;

    surnameResult = strcmp(me1->surname, me2->surname);

    return surnameResult;
}

不使用字符串库比较字符串。 此方法比较字符串是否相同,如果两个字符串相等,它将 return 值 0。在方法里面传入struct指针即可。

int compareStr(char *s, char *t)
{

    char t1 = *s;
    char t2 = *t;
    int x;

    while (t1 != '[=10=]' && t2 != '[=10=]') {
        x = (int)(t1 - t2);
        if (x ==0) {
            s++;
            t++;
            t1 = *s;
            t2 = *t;
        }
        else
        {
            break;
        }
    }


    return x;

}