CS50凯撒分段错误解释

CS50 Caesar segmentation fault explanation

我可以毫无问题地编译这段代码,现在的想法只是为了测试我是否可以在继续之前毫无问题地成功输入密码密钥(命令行参数)。我没有找到为什么我的代码总是 return 分段错误的运气,然后我看到了在第 4 行的 argv[1] 之前放置一个 '*' 的提示,这似乎解决了我所有的问题问题。有人可以向我解释这是为什么吗?

int main(int argc, string argv[]) // command line argument for the cipher key
{
    int key;
    if (argc == 2 && isdigit(*argv[1])) //the line in question
    {
        key = atoi(argv[1]); // convert the digit string into an integer
    }
    else
    {
        printf("Usage:./caeser key\n");
        return 1;
    }
printf ("%i\n",key);
}

then I saw a tip to put a '*' before argv[1] in the 4th line, and that seems to solve all my issues. Can someone please explain to me why this is?

这意味着,在您看到该提示之前,它看起来像这样:

isdigit(argv[1])

你在这里混用了类型。

argvchar*的数组。这意味着,argv[1]char* 类型。 但是 isdigit 需要 int 类型的参数。你应该得到一些编译器警告。 该函数期望获得 charEOF 范围内的值。传递指针很可能会提供一些超出范围的值。

如果添加 *,则取消引用 char 指针并获取该字符串的第一个字符。这正是 isdigit 所期望的,并且它可以正常工作。