为什么 space 没有在分配给存储要在程序中使用的 main 参数的指针变量之前分配?
Why is space not allocated before assignment for pointer variables that store the main's arguments that are to be used in the program?
我正在编写一个 C 程序,它要求我获取命令行参数并在程序中使用它们。我不明白的是,为什么在代码中,字符串参数被分配给一个 char*
变量,以便在程序中进一步使用,而这样做之前没有分配内存。在使用指针之前不需要为指向的指针分配足够的内存吗?
//c program
int main(int argc, char *argv[]){
//lets say there is only one argument after the program name
// so that argc = 2 and argv = {filename, string1}
//assigning the string to a char *
//no memory allocated before assignment
char *x = argv[1];
// rest of the program ...
}
argv
中的每个项目已经指向这样分配的 space,它是由一些 C 运行时支持创建的,用于存储命令行参数。因此,您可以使用指针安全地指向这些预先分配的缓冲区。
请注意,这也意味着您也不能尝试释放它们:创建它们的人将负责正确销毁它们。
我正在编写一个 C 程序,它要求我获取命令行参数并在程序中使用它们。我不明白的是,为什么在代码中,字符串参数被分配给一个 char*
变量,以便在程序中进一步使用,而这样做之前没有分配内存。在使用指针之前不需要为指向的指针分配足够的内存吗?
//c program
int main(int argc, char *argv[]){
//lets say there is only one argument after the program name
// so that argc = 2 and argv = {filename, string1}
//assigning the string to a char *
//no memory allocated before assignment
char *x = argv[1];
// rest of the program ...
}
argv
中的每个项目已经指向这样分配的 space,它是由一些 C 运行时支持创建的,用于存储命令行参数。因此,您可以使用指针安全地指向这些预先分配的缓冲区。
请注意,这也意味着您也不能尝试释放它们:创建它们的人将负责正确销毁它们。