这是我试图理解的一段代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
/* Spawn a child process running a new program. PROGRAM is the name
of the program to run; the path will be searched for this program.
ARG_LIST is a NULL-terminated list of character strings to be
passed as the program’s argument list. Returns the process ID of
the spawned process. */
int spawn (char* program, char** arg_list)
{
pid_t child_pid;
/* Duplicate this process. */
child_pid = fork ();
if (child_pid != 0)
/* This is the parent process. */
return child_pid;
else {
/* Now execute PROGRAM, searching for it in the path. */
execvp (program, arg_list);
/* The execvp function returns only if an error occurs. */
fprintf (stderr, “an error occurred in execvp\n”);
abort ();
}
}
int main ()
{
/* The argument list to pass to the “ls” command. */
char* arg_list[] = {
“ls”, /* argv[0], the name of the program. */
“-l”,
“/”,
NULL /* The argument list must end with a NULL. */
};
/* Spawn a child process running the “ls” command. Ignore the
returned child process ID. */
spawn (“ls”, arg_list);
printf (“done with main program\n”);
return 0;
}
我无法理解生成函数的指针如何工作。它要求的参数是 char* program
和 char** arglist
。在 main 方法中,我们调用该方法并传入 "ls"
和 char* arglist[]
,我理解它是一个指针数组。 char* program
如何对应于 "ls"
,因为 "ls"
不是指向 char
的指针。 char** arglist
(指向 char 的指针)如何与 char* arglist[]
(指针数组)相对应?
我只是无法理解此代码示例中的指针如何工作。
另外,在main
中,对于char* arg_list[]
,我们基本上是存储指向每个字符的指针吗?例如,arg_list[0]
将保存“l”
的地址,arg_list[1]
将保存“的地址s"
, arg_list[2]
将保存 "-"
最佳答案
您在代码中使用了智能引号。纠正它,并找出你得到它们的原因。它们完全是错误的,您的程序将无法使用它们进行编译。
从初始化器推导出长度的 char*
数组:
char* arg_list[] = {
这些元素是从字符串文字初始化的,它是一个以 0 结尾的不可修改 char
元素的数组。这些数组在使用时衰减为指向其第一个元素的指针:
"ls", "-l", "/", NULL };
顺便说一句:指针上下文中的NULL
是一个空指针常量。永远不要忘记将其转换到不明确的上下文中(省略号、无原型(prototype)函数)。
下面的两个数组在调用指向其第一个元素的指针时都会衰减:
spawn ("ls", arg_list);
顺便说一句:常量复合文字 (C99) 和字符串文字(永远)可以合并以节省空间。
关于您的 spawn()
函数,没什么可说的...
关于c - 在C中使用指针?使困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27412802/