一、问题来由
由以上疑问,演化成了“只在编译期确定的空间才会分配在栈上”的疑问,因为上面 argv 指向明显是编译期确定不了的,那会放在堆上吗?
二、讨论
在书上找到如下段落:
(1)栈内存用来保存定义在函数内的非static对象;
(2)静态内存用来保存局部static对象、类static数据成员以及定义在任何函数体职位的变量。
通过以上段落,可以得到如下结论:
main参数 *argv[] 指向不可能存在栈上
因为这块空间不是在栈内定义的,但是argv这个指针在main函数栈上。
三、真相
argv的申请和释放应该由系统来负责,是传入参数,算不上全局或者局部变量。所以这块内存就不在程序内部。
详见网站 http://publications.gbdirect.co.uk/c_book/chapter10/arguments_to_main.html:
There are at least two arguments to main: argc and argv. The first of these is a count of the arguments supplied to the program and the second is an array of pointers to the strings which are those arguments—its type is (almost) ‘array of pointer to char’. These arguments are passed to the program by the host system’s command line interpreter or job control language.
The declaration of the argv argument is often a novice programmer’s first encounter with pointers to arrays of pointers and can prove intimidating. However, it is really quite simple to understand. Since argv is used to refer to an array of strings
参考资料
[1] http://bbs.csdn.net/topics/390759615
[2] http://publications.gbdirect.co.uk/c_book/chapter10/arguments_to_main.html
[3] http://en.cppreference.com/w/cpp/language/main_function
[4] 我在quora提出的问题