12

In the proccess of learning C, I'm trying to write a program that accepts one of your environment variable as input, and outputs its value.

The question is, is there any way to know the length of envp? I mean, how many envp is there? I'm aware that it is a char** - an array of string. And finding the size of array in C is problematic already. What can I do to know the size of envp?

Please just provide direction, not the concrete answer (or code).

Community
  • 1
  • 1
bertzzie
  • 3,558
  • 5
  • 30
  • 41
  • 1
    `envp` is a `char**`, but it's not an "array of string". It's a pointer to the first element of an array of pointers, each of which is a pointer to (the first character of) a string -- except for the last, which is a null pointer and therefore doesn't point to anything. – Keith Thompson Jul 25 '13 at 18:30

3 Answers3

10

It's terminated by a NULL pointer. You have to count it if you want to know the length.

Ben Jackson
  • 90,079
  • 9
  • 98
  • 150
  • 3
    Or, in the OP's case, you could just iterate with your terminating condition as `envp[i] == NULL`. You'll have to iterate over the elements to find the one you want anyway, you don't really _need_ the length for that. – Chris Lutz Aug 11 '11 at 04:36
  • @Chris I wasn't sure how explicit to be when the question specifically asked for a hint. I guess now that the OP is satisfied I could edit for future visitors. – Ben Jackson Aug 11 '11 at 07:57
2

the value of argv[argc] == NULL that should give you a clue.

Griffin
  • 13,184
  • 4
  • 29
  • 43
  • That requires faith in consistency: that the POSIX environment vector is structured like the ISO C agrument vector. One's faith in consistency is severely tested by software on a daily basis. :) :) – Kaz Jul 25 '13 at 19:45
2

You should look into getenv(). It's more portable than manipulating envp, because environments like plan9 implement the environment differently, while preserving the behavior of this function.

Dave
  • 10,964
  • 3
  • 32
  • 54
  • Yes, but `getenv()` can't tell you which environment variables are defined. If you already know the name of the variable, `getenv()` is great; if not, you need to traverse the data structure that `envp` points to. – Keith Thompson Jul 25 '13 at 18:29