比较两个指针所指向的

时间:2013-05-27 21:28:32

标签: c++ pointers comparison

我正在编写一个检测网络钓鱼的程序。我正在尝试检查URL的基数,如果它在标记中是否相同。 对于例如在http://maps.google.com“> www.maps.yahoo.com  我正在尝试检查网址的最后两部分是否相同,即google.com = yahoo.com与否。

我正在使用以下代码:

void checkBase(char *add1, char *add2){
    char *base1[100], *base2[100];
    int count1 = 0, count2 = 0;
    base1[count1] = strtok(add1, ".");
        while(base1[count1] != NULL){
         count1++;
         base1[count1] = strtok(NULL, ".");
    }
    base2[count2] = strtok(add2, ".");
    while(base2[count2] != NULL){
    count2++;
    base2[count2] = strtok(NULL, ".");
    }
    if((base1[count1-1] != base2[count2-1]) && (base1[count1-2] != base2[count2-2])){
         cout << "Bases do not match: " << endl
          << base1[count1-2] << "." << base1[count1-1] << " and "
          << base2[count2-2] << "." << base2[count2-1] << endl;
    }
    else{
        cout << "Bases match: " << endl
              << base1[count1-2] << "." << base1[count1-1] << " and "
                  << base2[count2-2] << "." << base2[count2-1] << endl;

    }
 }

我不确定我在if语句中的比较是否正确。我正在传递两个URL。 感谢

2 个答案:

答案 0 :(得分:0)

这是比较两个指针 char * (正如你指出的那样;))

base1[count1-1] != base2[count2-1])

使用此代替

strcmp(base1[count1-1], base2[count2-1]) != 0

你可以使用 std:string 提升标记器(我认为现在是C ++ 11)

问候

答案 1 :(得分:0)

您无法通过比较字符串来比较字符串,两个相同的字符串可以存储在不同的地址中。为了比较它们,你应该strcmp:

 if(strcmp(base1[count1-1], base2[count2-1]) != 0 || 
    strcmp(base1[count1-2], base2[count2-2])!=0){
        std::cout << "Bases do not match: " << std::endl
            << base1[count1-2] << "." << base1[count1-1] << " and "
            << base2[count2-2] << "." << base2[count2-1] << std::endl;
    }

您可以使用C ++工具执行类似操作:

void checkBase(std::string a1, std::string a2){
    size_t a1_start = a1.rfind('.'), a2_start = a2.rfind('.');
    a1_start = a1.rfind('.', a1_start-1);
    a2_start = a2.rfind('.', a2_start-1);
    std::string h1 = a1.substr(a1_start+1), h2 = a2.substr(a2_start+1);
    if (h1 == h2)
        std::cout << "same" << std::endl;
    else
        std::cout << "not same" << std::endl;
}