Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!seismo!husc6!cca!mirror!datacube!ftw From: ftw@datacube.UUCP Newsgroups: comp.lang.c Subject: Re: Accessing argc & argv from a functi Message-ID: <102600009@datacube> Date: Fri, 17-Jul-87 13:13:00 EDT Article-I.D.: datacube.102600009 Posted: Fri Jul 17 13:13:00 1987 Date-Received: Sat, 18-Jul-87 20:48:41 EDT References: <22@flmis06.ATT.COM> Lines: 54 Nf-ID: #R:flmis06.ATT.COM:-2200:datacube:102600009:000:2122 Nf-From: datacube.UUCP!ftw Jul 17 13:13:00 1987 mikel@flmis06.UUCP writes: > /* ---------- "Accessing argc & argv from a functi" ---------- */ > I recently ran accross an interresting question. > How does one get at argc and argv (and possibly envp) from a function? > Without declaring it in main first, and then passing a pointer (global > or not)! Assume you don't have control over what happens in main. Can > you still get at the argument vector? > -- > Mikel Manitius @ AT&T Network Operations > mikel@codas.att.com.uucp | attmail!mikel The environment pointer can either be passed through as the third argument to main(), as you mention, or can be accessed (in a lot of implementations but perhaps not all) by the following declaration: extern char *environ; in either the function where you need it, or globally. This is usually how the getenv() function is implemented. Speaking of getenv(), if you want the definition of a single environment variable, you can use this: char *path; . . . path = getenv("PATH"); which searches through the string pointed to by "environ" to find something of the form "PATH=", and returns a pointer to the char following the "=". This all makes a few assumptions about how your libraries (and OS) maintain environment variables, but I have not seen many that didn't work this way. As for argc and argv: they are usually gathered by the runtime startup code which will push them on the stack before the runtime startup calls your main() function. Note also the the runtime startup will push the environment pointer before calling main(). There is usually no way to get at "argv" and "argc" without declaring them as arguments to main(). One "cheap and dirty" thing you could do though is to get the value for environ and walk back up the stack. You would stop when you finish walking over the program name. This way, you could possibly re-build argc and argv without passing them through main(). (Why do I hear LOTS of groaning in the background?? ;-)) Of course, this is *VERY* non-portable and assumes a great deal about the ordering of objects on the stack. Hope this helps... Farrell