Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 这个指针安全返回吗?_C_Pointers_Scope_Atoi - Fatal编程技术网

C 这个指针安全返回吗?

C 这个指针安全返回吗?,c,pointers,scope,atoi,C,Pointers,Scope,Atoi,几天前,我想找到一个安全的替代atoi的方法,并找到以下代码作为对问题的回答: #include <assert.h> #include <ctype.h> #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> typedef enum { STR2INT_SUCCESS, STR2INT_OVERFLOW

几天前,我想找到一个安全的替代
atoi
的方法,并找到以下代码作为对问题的回答:

#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

typedef enum {
    STR2INT_SUCCESS,
    STR2INT_OVERFLOW,
    STR2INT_UNDERFLOW,
    STR2INT_INCONVERTIBLE
} str2int_errno;

str2int_errno str2int(int *out, char *s, int base) {
    char *end;
    if (s[0] == '\0' || isspace(s[0]))
        return STR2INT_INCONVERTIBLE;
    errno = 0;
    long l = strtol(s, &end, base);
    /* Both checks are needed because INT_MAX == LONG_MAX is possible. */
    if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX))
        return STR2INT_OVERFLOW;
    if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN))
        return STR2INT_UNDERFLOW;
    if (*end != '\0')
        return STR2INT_INCONVERTIBLE;
    *out = l;
    return STR2INT_SUCCESS;
}


int main(void) {
  int i;
    /* Lazy to calculate this size properly. */
    char s[256];

    /* Simple case. */
    assert(str2int(&i, "11", 10) == STR2INT_SUCCESS);
    assert(i == 11);
    printf("%i", i);

    /* Negative number . */
    assert(str2int(&i, "-11", 10) == STR2INT_SUCCESS);
    assert(i == -11);
}
#包括


这不是不安全吗?因为out指针被设置为函数中本地定义的变量
这难道不意味着一旦转换完成,局部变量超出范围,它就会被覆盖,我们就不能再依赖这个值了吗


我可能只是错过了一些东西,但目前我不明白这是一种安全的方式

*out=l不设置
输出
,它设置
*输出
。也就是说,
out
已经指向的是什么,因为它取消了指针的引用。只要传入有效地址,函数就会修改非本地对象。

参数是指向
main
中变量
i
的指针。稍后执行此操作时:

*out = l;
这不会更改
out
,而是取消引用它并更改它指向的变量,即
main
中的
i
。因此,当函数返回时,
i
将被修改

如果
out
指向
str2int
中的局部变量,则会出现指针指向无效内存的问题