linux getenv路径目录,getenv的返回值是存放在哪里的,该怎么处理
getenv的返回值是存放在哪里的
参考代码如下:
#include
#include
int main(void)
{
char *s;
s=getenv("COMSPEC"); /* get the comspec environment parameter */
printf("Command processor: %s\n",s); /* display comspec parameter */
return 0;
}
来源于好搜百科
问题1:事先不需要对s进行内存分配吗?
问题2:据说getenv的返回值是存在于一个全局的二维数组中的,这个二维数组和函数中的*s又是如何联系的呢
------解决思路----------------------
char *
getenv (name)
const char *name;
{
size_t len = strlen (name);
char **ep;
uint16_t name_start;
if (__environ == NULL
------解决思路----------------------
name[0] == '\0')
return NULL;
if (name[1] == '\0')
{
/* The name of the variable consists of only one character. Therefore
the first two characters of the environment entry are this character
and a '=' character. */
#if __BYTE_ORDER == __LITTLE_ENDIAN
------解决思路----------------------
!_STRING_ARCH_unaligned
name_start = ('=' <
------解决思路----------------------
*(const unsigned char *) name;
#else
name_start = '='
------解决思路----------------------
((*(const unsigned char *) name) <
#endif
for (ep = __environ; *ep != NULL; ++ep)
{
#if _STRING_ARCH_unaligned
uint16_t ep_start = *(uint16_t *) *ep;
#else
uint16_t ep_start = (((unsigned char *) *ep)[0]
------解决思路----------------------
(((unsigned char *) *ep)[1] <
#endif
if (name_start == ep_start)
return &(*ep)[2];
}
}
else
{
#if _STRING_ARCH_unaligned
name_start = *(const uint16_t *) name;
#else
name_start = (((const unsigned char *) name)[0]
------解决思路----------------------
(((const unsigned char *) name)[1] <
#endif
len -= 2;
name += 2;
for (ep = __environ; *ep != NULL; ++ep)
{
#if _STRING_ARCH_unaligned
uint16_t ep_start = *(uint16_t *) *ep;
#else
uint16_t ep_start = (((unsigned char *) *ep)[0]
------解决思路----------------------
(((unsigned char *) *ep)[1] <
#endif
if (name_start == ep_start && !strncmp (*ep + 2, name, len)
&& (*ep)[len + 2] == '=')
return &(*ep)[len + 3];
}
}
return NULL;
}
libc_hidden_def (getenv)
这是glibc源码里面getenv的实现代码,自己看看吧。
发布者:admin,转转请注明出处:http://www.yc00.com/news/1693003467a670867.html
评论列表(0条)