You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50 Pset2:Crack中crypt()返回值无法用==比较的问题求助

Why == Doesn't Work for Comparing crypt() Results in CS50

Hey there! Let's break down why your condition isn't triggering and how to fix it—since you're only two weeks into CS50, this is a super common (and totally understandable) gotcha with C strings.

First, remember that in CS50, string is just an alias for char* (a pointer to a character). When you use == to compare two string variables, you're not checking if their text content is the same—you're checking if they point to the exact same spot in memory.

Here's what's happening in your code:

  • x is a string literal ("50AWs/7oe6pkA") that gets stored in a read-only section of your program's memory, with a fixed address.
  • a is the pointer returned by crypt(), which points to a separate chunk of memory (either a static buffer or heap-allocated space) where the hashed result lives.

Even though the text in both locations is identical, their memory addresses are different. So a == x evaluates to false, hence no "true" output.

The Fix: Use strcmp()

To compare the actual content of two C strings, you need to use the standard library function strcmp(). It checks each character of the strings one by one and returns:

  • 0 if the strings are exactly equal
  • A negative number if the first string is "less than" the second (by ASCII value)
  • A positive number if the first string is "greater than" the second

Here's your updated code:

#include <cs50.h>
#include <stdio.h>
#include <string.h>  // Required for strcmp()

int main(int argc, string argv[]) {
    string key = "f";
    string salt = "50";
    string a = crypt(key, salt);
    string x = "50AWs/7oe6pkA"; // this is the hash output from crypt(f, 50)
    
    if (strcmp(a, x) == 0) {  // Check if strcmp returns 0 (strings match)
        printf("true\n");
    }
    return 0;
}

Run this, and you'll get the "true" output you expected.

Quick Recap for New CS50 Students

  • string = char* = a pointer that stores the memory address of the first character of your string
  • == compares pointer addresses, not string content
  • Always use strcmp() when you need to check if two C strings have the same text

内容的提问来源于stack exchange,提问作者tfu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:11:37