在C中使用指针?困惑

时间:2014-12-10 23:28:50

标签: c arrays pointers exec fork

这是我试图理解的一段代码:

#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;
}

我无法理解spawn函数的指针是如何工作的。它要求的参数是char* programchar** 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]将保留"-"的地址< / p>

1 个答案:

答案 0 :(得分:1)

您在代码中使用智能引号。纠正这一点,并找出你获得它们的原因。它们完全错了,你的程序不会用它们编译。

从初始化程序推导出的char*长度数组:

char* arg_list[] = {

元素是从字符串文字初始化的,字符串文字是由0个终止的不可修改的char元素数组。那些数组在使用时会衰减指向它们的第一个元素:

   "ls", "-l", "/", NULL };
BTW:指针上下文中的NULL是一个空指针常量。永远不要忘记在模糊的上下文(省略号,无原型函数)中进行投射。

以下两个数组在调用指向其第一个元素的指针时会衰减:

spawn ("ls", arg_list);

BTW:可以合并常量复合文字(C99)和字符串文字(永远),以节省空间。

关于你的spawn() - 函数......

,没什么可说的