Search code examples
c++environmentargv

Confusion about argc argv and env


I just don't know how to explain my question precisely. So I wrote that title above.

Here is my confusion about a very simple program. Exactly, the results.

#include <iostream>
using namespace std;

char * tmp[]={"aaa", "bbb", "ccc"};//there are 3 members

int main(int argc, char* argv[], char* env[])
{
    cout << sizeof(env)/sizeof(char*) << endl;
    cout << sizeof(tmp)/sizeof(char*) << endl;
}

Results:1 3

What I want is the length of env[]. How can this possible that I got number 1 of env[], while the length of 'tmp'(3) is absolutely rigth.

There's no way that the length of env is 1, cause I tested it and the number is 47.

Why this happened? Thanks!


Solution

  • The difference is that tmp is an array, whereas env is a pointer. Arrays and pointers are different. It's a bit confusing because array syntax in a function formal parameter list is actually a pointer in disguise.

    There is no way to get the number of elements pointed to by env using sizeof. You have to go through them until you find the NULL element terminating the list.