【问题标题】:Using pointers in C? Confused在 C 中使用指针?使困惑
【发布时间】:2014-12-10 23:28:49
【问题描述】:

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

#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] 将保存"-" 的地址

【问题讨论】:

  • C 字符串是一系列以 0 结尾的字符,因此您可以通过指向字符串中第一个字符的指针来引用它们。同样,数组是连续内存位置中的一系列值,因此char[](或多或少)等同于char*
  • 仅供参考,arg_list[0] 是指向 "ls" 的指针,arg_list[1] 是指向 "-l" 的指针,arg_list[2] 是指向 "/" 的指针,arg_list[4] 是 @ 987654349@指针。
  • @Rup:多于少。并且知道确切的差异很重要。
  • 顺便说一句:当心你使用的不那么聪明的智能报价。他们错了。
  • 顺便说一句:“an error occurred in execvp\n” 你有奇怪的引号。

标签: c arrays pointers exec fork


【解决方案1】:

您在代码中使用了智能引号。纠正那个,找出你为什么得到它们。它们完全是错误的,您的程序将无法使用它们进行编译。

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

char* arg_list[] = {

这些元素是从一个字符串文字初始化的,它是一个以 0 结尾的不可修改的 char-元素数组。这些数组在使用时衰减为指向它们的第一个元素的指针:

   "ls", "-l", "/", NULL };

顺便说一句:指针上下文中的NULL 是一个空指针常量。永远不要忘记将其转换为模棱两可的上下文(省略号、无原型函数)。

下面的两个数组在调用指向它们的第一个元素的指针时都会衰减:

spawn ("ls", arg_list);

顺便说一句:常量复合文字 (C99) 和字符串文字(从永远开始)可以合并以节省空间。

关于你的spawn()-function 没什么好说的...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    相关资源
    最近更新 更多