我正在编写一个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
中的每个项目都已指向这样的已分配空间,该空间是由某些C运行时支持创建的,用于存储命令行参数。因此,您可以使用指针安全地指向这些预分配的缓冲区。
请注意,这也意味着您不能尝试解除分配它们:创建它们的人将负责正确销毁它们。