错误返回修改指针

Error Returning Modified Pointer

我对 C 编程还很陌生。经过几个小时的研究,我遇到了一个问题,但仍然无法解决。如果您需要示例,我将在下面粘贴我的(基本)源代码。问题基本上如下:

我有一个方法 returns 1 表示成功,否则为 0。它接受一个用作函数实际 return 值的 int 指针,这意味着传递的指针由该方法修改。稍后我需要使用修改后的值。该行为应类似于 fgets 或 scanf 等函数中的缓冲区指针。在我尝试 return 来自调用函数的修改后的指针值之前,这工作正常。我收到一个访问冲突错误,并且 int 值是负最大值,resp。不明确的。我该怎么做才正确?

我之前读过有关双指针的内容,但无法弄清楚如何将此技术合并到我的程序中...双指针是正确的方法吗?

下面是我的源码供参考:)

int validateInteger(int *out) {
    char buffer[17];
    fgets(buffer, 16, stdin);
    if (sscanf(buffer, "%d")) {
        *out = atoi(buffer);
        return 1;
    }
    return 0;
}

int anotherFunction() {
    int selection = 0;

    while(1) {
        printf("Print something...");

        if (validateInteger(&selection) && selection >= 0 && selection <= 7) {
            break;
        } else {
            clearScreen();
        }
    }
    return selection;
}

int main() {

    while(1) {
        int sel = anotherFunction(); // THIS IS WHAT DOESN'T WORK!

        switch (sel) {
        case 0:
            return 0;
        default:
            printf("Print some error msg here...");
            return 1;
        }
    }
}

如有任何帮助,我们将不胜感激。 提前谢谢大家!

您对 sscanf() is wrong!! You never passed the address of the variable to store the scanned value. This invokes undefined behaviour.

的使用

根据 C11 标准,章节 §7.21.6.2,

[..] If there are insufficient arguments for the format, the behavior is undefined.

您需要提供变量来保存扫描值,例如R Sahu提到的

if (sscanf(buffer, "%d", out) == 1) {
   return 1;
}

问题出在以下几行:

if (sscanf(buffer, "%d")) {
    *out = atoi(buffer);
    return 1;
}
  1. 您不需要同时使用 sscanfatoi。您只需要使用其中之一。
  2. 您忘记将 out 传递给 sscanf。当格式字符串包含 %d 时,函数会查找指向 int 的指针以将数据读入其中。由于您没有传递该参数,程序会导致未定义的行为。在您的情况下,它会导致访问冲突错误。

使用

if (sscanf(buffer, "%d", out) == 1) {
   return 1;
}

您也可以使用以下行代替前面的行。

*out = atoi(buffer);
return 1;

但是,使用此方法检查错误的唯一方法是检查 *out 的值是否为 0。如果 0 是合法值,则使用第二种方法并不好。因此,我推荐第一种方法。