0

I'm trying to write my own version of getenv. I haven't started yet so I'm trying to understand environ first.

If it's a global why can't I print it in my function? Is environ a String or an array of chars? Why is environ a double pointer? Thank you.

#include <iostream>
#include <string>
#include <stdlib.h>
void myenv(char*);

void myenv(char* name)
{
std::cout<<environ;
}

int main(int argc, char** argv, char** environ)
{
myenv("PATH");
}
Rich
  • 5,603
  • 9
  • 39
  • 61
Sal Rosa
  • 551
  • 2
  • 8
  • 12

3 Answers3

2

environ is a char**. It points at an array of char*, each of which points to a string of char. So it's like an array of strings. For example, environ[0] is a null-terminated string. Try printing out that:

std::cout << environ[0];

Each string is an environment variable of the form name=value. They correspond to the environment variables for the current process.

However, environ is not a feature of C++ and is non-portable. It comes from the unistd.h header which is defined by POSIX.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
1

Its a char ** containing the env. variables

extern char **environ;

http://pubs.opengroup.org/onlinepubs/007908799/xsh/environ.html

Tom
  • 43,810
  • 29
  • 138
  • 169
0

Just adding;

Is environ a String or an array of chars? Why is environ a double pointer?

environ addresses an array of pointers, that each point to the first address of a character string. The environment isn't one string, it is a bunch of strings (well, the environment could be empty, so that "bunch" can be zero).

environ[0] contains a pointer to the 'first' environment variable.
environ[1] contains a pointer to the 'second'.

environ[0][0] would reference the first character of the 'first' name in the environment.
environ[1][0] would reference the first character of the 'second' name.

Or if there isn't at least two environment variables, environ[1] points off into segfault land or worse, random memory.

I quoted first and second, as there are no defined rules as to how environment name strings are ordered, (don't expect the names to be alphabetical order for instance).

Brian Tiffin
  • 3,978
  • 1
  • 24
  • 34