动态参数传递给C中的execlp()函数

为简单起见,我修改了我的程序。 我想要做的是在运行时接受任意数量的参数并将其传递给execlp() 。 我正在使用固定长度的2d数组m[][]这样任何未使用的(剩余)槽可以作为NULL传递给execlp (在这种情况下为m[2][] )。

 #include #include #include #include int main() { char m[3][5], name[25]; int i; strcpy(name, "ls"); strcpy(m[0], "-t"); strcpy(m[1], "-l"); //To make a string appear as NULL (not just as an empty string) for(i = 0; i < 5; i++) m[2][i] = '\0'; // or m[2][i] = 0 (I've tried both) execlp(name, m[0], m[1], m[2], '\0', 0, NULL); // Does not execute because m[2] is not recognized as NULL return 0; } 

我该怎么做?

既然你想接受任意数量的参数,你应该使用的是execvp()而不是execlp()

 #include  #include  #include  #include  #include  int main(void) { char *argv[] = { "ls", "-l", "-t", 0 }; execvp(argv[0], argv); fprintf(stderr, "Failed to execvp() '%s' (%d: %s)\n", argv[0], errno, strerror(errno)); return(EXIT_FAILURE); } 

execvp()函数采用数组forms的任意长度参数列表,与execlp()不同,其中您编写的任何单个调用仅使用固定长度的参数列表。 如果要容纳2,3,4,…参数,则应为每个不同数量的参数编写单独的调用。 其他任何事情都不完全可靠。

 #include  #include  #include  #include  int main() { char *args[] = {"ls", "-t", "-l" }; execlp(args[0], args[0], args[1], args[2], NULL); perror( "execlp()" ); return 0; } 

为简单起见,我用固定指针数组替换了所有字符串管理内容。 execlp()只需要一个最后的NULL参数,execle()在NULL arg 之后也需要环境指针。

  char m[3][5]; 

这是一个2D字符数组。

 m[2] is a element of the 2D array that is it it a 1D Array of characters. 

所以它总是有一个常量地址。它永远不会是NULL,因为它是一个不能为NULL的常量地址。它不能分配给NULL,所以你必须使用NULL作为最后一个参数。

execlp()使用NULL作为终止参数,因此您必须提及它。

如果使用命令行参数,则最后一个命令行参数始终为NULL。char * argv []参数的最后一个元素可以用作execlp()函数中的终止参数。