简体   繁体   English

如何在C中比较两个指针的值

[英]How to compare the values of two pointers in C

My function below always returns true. 我下面的函数总是返回true。 I assume is because I'm comparing pointers. 我猜想是因为我在比较指针。 How can I compare the values and not just the pointers. 我该如何比较这些值,而不仅仅是指针。

struct Card {
    const char *suit;
    const char *face;
};

...
struct Card hand[HAND_SIZE];
...

//Determine whether the hand contains a pair.
bool hasPair(struct Card wHand[]) {
    bool result = false;
    for (unsigned i = 0; i < HAND_SIZE; ++i) {
        for (unsigned j = 0; j < HAND_SIZE; ++j) {
            if(wHand[i].face == wHand[j].face && wHand[i].suit == wHand[j].suit) {
                result = true;
            }
        }
    }
    return result;
}

The biggest problem with this algorithm is that you are comparing the card with itself: you start both i and j at zero, so you get false positives for pairing each card with itself. 该算法的最大问题是您正在将卡与自身进行比较:将ij都从零开始,因此将每张卡与自身配对时会出现误报。

A simple fix to this is to start j at i+1 , ensuring that only different cards get compared. 一个简单的解决方法是将ji+1 ,以确保仅比较不同的卡。

Since setting result to true is a one-way street, consider returning true as soon as you find a match: 由于将result设置为true是一条单向街道,因此请考虑在找到匹配项后立即返回true

for (unsigned i = 0; i < HAND_SIZE; ++i) {
    for (unsigned j = i+1; j < HAND_SIZE; ++j) {
        if(wHand[i].face == wHand[j].face && wHand[i].suit == wHand[j].suit) {
            return true;
        }
    }
}
return false;

Note: This assumes that face and suit are set to string constants in the same code, which may be fragile if you link multiple object files. 注意:这假定在同一代码中将facesuit设置为字符串常量,如果链接多个目标文件,则该字符串可能会很脆弱。 A much safer option for this would be using an enum for face and suit representation, and making an array of string representations for each enum value: 一个更安全的选择是将enum用于面部和西服表示,并为每个enum值制作一个字符串表示数组:

enum Face {
    Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace
};
enum Suit {
    Spades, Clubs, Diamonds, Hearts
};
struct Card {
    enum Face face;
    enum Suit suit;
};

result is set to true in the first (and, as it happens, in every) iteration of your i loop, given that at some point in each iteration, j==i and therefore you're comparing the same array element with itself. result被设置为true的第一个(和,因为它发生在每一个)的i循环迭代,因为在每次迭代中的某个时刻, j==i ,因此,你要比较自身相同的数组元素。 You should only execute your if statement when i!=j . 您仅应在i!=j时执行if语句。

To your original point though, you're not comparing pointers - you are comparing the actual values. 不过,就您的原始观点而言,您并不是在比较指针,而是在比较实际值。 The array [ ] square brackets serve to dereference the pointer; 数组[]方括号用于取消引用指针;
wHand[i] does the same thing as *(wHand + i) . wHand[i]*(wHand + i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM