Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: sizeof environment variables array = 1? Date: Thu, 08 Jun 2017 09:34:44 -0700 Organization: None to speak of Lines: 66 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="014809c4f49cfafbe03afa6d23552d79"; logging-data="9590"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19bOkzOy1buqCqnx9b42FzG" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:5yWpbb7Ag50vWsayEy/bs8USPpQ= sha1:0ykSu8PJSHg/WtVrAMxrfd2DhzQ= Xref: csiph.com comp.lang.c:111832 Lew Pitcher writes: > DFS wrote: >> int main(int argc, char *argv[], char *env[]) >> { >> printf("%d\n",sizeof(env)/sizeof(env[0])); Should be "%zu\n", not "%d\n" -- or you could use "%d\n" and cast the argument to int. >> return(0); >> ) >> >> Output is 1. >> >> Why? > > Given > char *env[]; > then > env is a pointer (to a pointer to char) > and > env[0] is also a pointer (to a char) `char *env[]` normally makes env an array of char* pointers, but because it's a parameter declaration it's "adjusted" to become a pointer. This: int main(int argc, char *argv[], char *env[]) is exactly equivalent to this: int main(int argc, char **argv, char **env) Given a pointer to the initial element of an array, you can't use sizeof to determine the number of elements in that array. You can traverse the array elements to find the length *if* there's a consistent convention marking the end of the array (typically a null pointer for an array of pointers, or a null character for an array of characters). Incidentally, this declaration of main is not portable, but an optional third "env" parameter is a common extension. > Apparently, in your execution environment, > a >>pointer to a pointer to char<< is the same size as a >>pointer to char<< > and, thus, division of the size of one by the size of the other gives a > value of 1 In principle, it could still yield 1 if, for example, sizeof (char**) == 6 and sizeof (char*) == 4. But that detail in understanding the semantics of this semantically incorrect code is less important than fixing the code. >> If I add: >> >> while (*env) {printf("%s\n", *env++);} >> >> it prints out all 65 of them. Because it scans for the null pointer that conventionally marks the end of the array. If the program were invoked with an `env` data structure that isn't properly terminated, you'd have undefined behavior. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"