c - 如何使用从 scanf 获取的参数填充字符指针数组?

标签 c arrays shell printf char-pointer

我正在尝试用 C 语言编写一个非常基本的 shell 程序。我面临的问题是尝试用从输入中获取的单词填充我的 argv 字符指针数组。当我尝试使用下面的 parse() 函数填充 argv 数组的内容后尝试打印出该数组的内容时,出现段错误。我知道这意味着我可能正在尝试访问超出范围的 argv 数组的一部分。然而,即使只提供一个参数来填充数组,我仍然会遇到段错误。用于打印 argc 的 printf 调用根据输入返回 argc 的正确值,但使用 *argv[0] 的第二个 printf 调用导致了段错误。我想知道我的错误是否是因为我尝试打印 argv 的内容,或者错误是因为我试图错误地填充 argv。

编辑:我应该补充一点,getword() 函数接受一行文本并返回由空格分隔的第一个单词以及许多其他分隔符。如有必要,我可以发布所有分隔符来分隔单词,但我不认为问题是由于 getword() 造成的。

编辑2:添加到头文件中并在main中包含#include语句。

编辑3:在main()下添加了getword函数,在p2.h下面添加了getword.h

这里是 p2.h,main 中包含的头文件:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "getword.h"
#include <signal.h>

#define MAXITEM 100

getword.h:

#include <stdio.h>
#include <string.h>
#include <strings.h>

#define STORAGE 255

int getword(char *w);

int parse(char *, char *[]);

主要功能如下:

#include "p2.h"
int main() {
    pid_t pid, child_pid;
    int argc, inputRedirect;
    char *devNull;
    devNull = (char *) malloc(10);
    strcpy(devNull, "/dev/null");
    char *argv[MAXITEM];
    char commandLine[STORAGE];


    for (;;) {
        printf("p2: ");
        scanf("%s", commandLine);
        argc = parse(commandLine, argv);
        printf("argc = %d\n", argc);

        if(argc == 0)
            continue;
        printf("*argv = %s\n", *argv[0]);
        child_pid = fork();
        if (child_pid < 0) {
            printf("Cannot fork! Terminating...");
            exit(1);
        } else if (child_pid == 0) {
            inputRedirect = open(devNull, O_RDONLY);
            dup2(inputRedirect, STDIN_FILENO);
            close(inputRedirect);
            execvp(*argv, argv);
        }
        else {
            for(;;) {
                pid = wait(NULL);
                if(pid == child_pid)
                   break;
            }
            printf("Child's pid is %d\n", child_pid);
        }
    }
    killpg(getpid(), SIGTERM);
    printf("p2 Terminated.\n");
    exit(0);
}

int parse(char *commandLine, char *argv[]) {
    int i, argc = 0;
    char *commandPointer = commandLine;
    while (*commandPointer != '\0') {
        *argv = commandPointer;
        argc++;
        getword(commandPointer);
    }
    *commandPointer = '\0';
    *argv = '\0';
    return argc;
}

getword.c:

#include "getword.h"
#include <stdlib.h>

/*Function Prototypes*/
int tilde(char *p, int i);
int BSFollowedByMetaCharacter(int c, char *w);


int getword(char *w) {

    int c;
    int index = 0;

    /*This while loop removes all leading blanks and whitespace characters
     * The if statement then tests if the first character is a new line or
     *  semicolon metacharacter*/
    while ((c = getchar()) == ' ' || c == '\t' || c == '\n' || c == ';') {
        if (c == '\n' || c == ';') {
            w[index] = '\0';
            return 0;
        }
    }

    /*This if statement calls ungetc() to push whatever character was taken
     * from the input stream in the previous while loop back to the input
     * stream. If EOF was taken from the input stream, ungetc() will return EOF,
     * which will then cause getword() to return -1, signalling that it reached
     * the End Of File. */
    if (ungetc(c, stdin) == EOF)
        return -1;

    /*This if statement deals with some of the "non-special" metacharacters.
     * If one of these metacharacters is pulled from the input stream by getchar(),
     * it is stored in w and null-terminated. getword() then returns the length of
     * the current string stored in w. If getchar() pulls anything besides one of the
     * specified metacharacters from the input stream, it is then returned using ungetc() after
     * the if statement.*/
    if ((c = getchar()) == '<' || c == '>' || c == '|' || c == '&') {
        w[index++] = c;
        int d = getchar();
        if (c == '>' && d == '>')
            w[index++] = d;
        else {
            ungetc(d, stdin);
        }
        w[index] = '\0';
        return index;
    }
    ungetc(c, stdin);

    /*This while statement handles plain text from the input stream, as well as a few 'special'
     * metacharacters. It also ensures that the word scanned is shorter than STORAGE-1 bytes.*/
    while ((c = getchar()) != ' ' && c != '<' && c != '>' && c != '|'
        && c != ';' && c != '&' && c != '\t' && c != '\n' && c != '\0'
        && index <= STORAGE - 1) {
        if (c == '~') {
            int *ip = &index;
            index = tilde(&w[index], *ip);
            continue;
        }/*END IF*/
        else if (c == '\\') {
            int d = c;
            c = getchar();
            if (BSFollowedByMetaCharacter(c, w)) {
                w[index++] = c;
                continue;
            } else {
                w[index++] = d;
            }

        }/*END ELSE IF*/
        w[index] = c;
        index++;
    }/*END WHILE*/

    ungetc(c, stdin);/*This final ungetc() call is used to push any meta characters*/
    w[index] = '\0'; /*used as delimiters back to the input stream, to be retrieved*/
    return index;    /*at the next call of getword().                                      */
}/*END getword()*/

int tilde(char *cp, int i) {
    int *ip;
    ip = &i;
    char *p = cp;
    char *o;
    o = (strcpy(p, getenv("HOME")));
    int offset = strlen(o);
    *ip = *ip + offset;
    return i;
}

int BSFollowedByMetaCharacter(int c, char *w) {
    if (c == '~' || c == '<' || c == '>' || c == '|' || c == ';' || c == '&'
        || c == ' ' || c == '\t' || c == '\\') {
        return 1;
    } else {
        return 0;
    }
}

最佳答案

getword.c 中的函数似乎是正确的。您的问题出在函数 parse 中。

要使用execvpargv的内容应如下(输入:“hello world”):

argv[0] -> "hello"
argv[1] -> "world"
argv[2] -> NULL

这里,argv是一个字符指针数组。但是,在 parse 函数中,您将 argv 视为简单的字符指针:

*argv = commandPointer;

这里:

*argv = '\0';

将解析函数更改为如下所示:

int parse(char *commandLine, char *argv[]) {
    int argc = 0;
    char *commandPointer;
    argv[argc++] = commandLine;

    do{
        commandPointer = (char*)malloc(sizeof(char) * STORAGE);
        argv[argc++] = commandPointer;
        getword(commandPointer);
    }while(*commandPointer != '\0');
    argv[argc] = NULL;
    return argc;
}

现在,您应该在 if-else 树之后释放分配的内存,如下所示:

for(int i = 0; i < argc; i++) free(argv[i]);

关于c - 如何使用从 scanf 获取的参数填充字符指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20186078/

相关文章:

c - 异常: Access violation writing location when using strcpy_s

ruby-on-rails - ActiveRecord 查询数组交集?

读取文本文件时Java不返回值

arrays - Ansible 解析来自 Register 的 JSON 数组

linux - 文件上的 sed 等同于变量

c - 如何使用gzip压缩和分块传输编码修复来自c套接字http服务器的图像中的怪异变形

c - 当我将相同的代码放在一个函数中与将它内联写入 C 中时,结果不同

c++ - 使用 C/C++ 检查 Windows 中的软件安装和安装目录

linux - cp 文件时如何将最后一个主题日期附加到文件名后缀

linux - 用linux文件中的字符串替换字符串模式