【问题标题】:How does the *getenv function actually works when passing "PATH" as parameter?将“PATH”作为参数传递时,*getenv 函数实际上是如何工作的?
【发布时间】:2022-01-05 08:36:38
【问题描述】:

根据tutorialsonpoint.com

*getenv 函数搜索指向的环境字符串 name 并将关联的值返回给字符串。

其中 name 是包含所请求变量名称的 C 字符串

该页面在该描述之后提供了一个简单示例,但该示例并未逐步解释此功能的实际工作原理。于是我在网上找了这个函数的代码,我设法得到了一个名为*_getenv*getenv函数的“副本”,这里是:

char *_getenv(const char *name)
{
    int i, j;
    int status;

for (i = 0; environ[i] != NULL; i++)
{
    status = 1;
    for (j = 0; environ[i][j] != '='; j++)
    {
        if (name[j] != environ[i][j])
        {
            status = 0;
            break;
        }
    }

    if (status)
    {
        return (&environ[i][j + 1]);
    }
}
return (NULL);
}

getEnv = _getenv("PATH");

我知道变量environ 指向一个称为“环境”的字符串指针数组。此数组中的最后一个指针具有值NULL。这意味着,在第一个 for 循环中,此函数将遍历数组,直到找到名为 NULLNAME

我不明白的是在第二个 for 循环中发生了什么,最终要满足的条件是 environ[i][j] != '=' 以及返回 (&environ[i][j + 1])if 语句,我的意思是,为什么返回地址时j计数器加1

【问题讨论】:

  • 第二个循环实际上是在执行memcmp,而j + 1索引指的是环境变量value的第一个字符,即equals之后的所有内容签名。

标签: c path environment-variables


【解决方案1】:

第二个for循环会发生什么,

该函数检查=之前的值是否等于name

name       = "somevariable"
environ[i] = "somevariable=somevalue"
              ^^^^^^^^^^^^
              ^^^^^^^^^^^^ ----------- are these parts equal?

所以比较name的每个字节是否等于environ[i]直到environ[i][??] = '=',所以:

bool are_equal = true; // assume they are equal
for (j = 0; environ[i][j] != '='; j++) { // for each character in environ[i] up until equal sign
    if (name[j] != environ[i][j]) { // check if bytes are equal
        are_equal = false; // if they are not, we notify and break
        break;
    }
}
if (are_equal) { do_smthg() }

为什么返回地址时j计数器加1?

environ[i][j] 指向'='

environ[i] = "somevariable=somevalue"
                          ^ ------------ [j]
                           ^ ----------  [j + 1]

我们要返回指向值的指针,不包括=符号,所以函数返回指向envron[i][j+1]的指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 2020-09-07
    • 2013-09-19
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多