According to tutorialsonpoint.com:
The
*getenv
function searches for the environment string pointed to by name and returns the associated value to the string.
Where name is the C string containing the name of the requested variable
That page provides a simple example after that description, but such example doesn't explain step by step how this function actually works. So I seeked the code of this function in the net, and I managed to get a "replica" of the *getenv
function called *_getenv
, here it is:
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");
I know that the variable environ
points to an array of pointers to strings called the "environment". The last pointer in this array has the value NULL
. Meaning that, in the first for cycle this function will loop over the array until it finds a NAME
called NULL
What I don't get is what happens in the second for cycle, where the final condition to be met is environ[i][j] != '='
and also the if statement where (&environ[i][j 1])
is returned, I mean, why is it adding 1 to the j counter when returning the address?
CodePudding user response:
what happens in the second for cycle,
The function checks if the value before =
is equal to name
.
name = "somevariable"
environ[i] = "somevariable=somevalue"
^^^^^^^^^^^^
^^^^^^^^^^^^ ----------- are these parts equal?
So compare if each byte of name
is equal to environ[i]
up until environ[i][??] = '='
, so:
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() }
why is it adding 1 to the j counter when returning the address?
environ[i][j]
points to '='
.
environ[i] = "somevariable=somevalue"
^ ------------ [j]
^ ---------- [j 1]
We want to return the pointer to the value, excluding the =
sign, so the function returns a pointer to envron[i][j 1]
.