【问题标题】:Get the first element of pointer array in C?获取C中指针数组的第一个元素?
【发布时间】:2017-06-25 23:22:49
【问题描述】:

我一直在寻找如何做到这一点。到目前为止,我发现的方法还没有取得成功。

GNU Readline Info

在该页面中,有一个名为 fileman.c 的示例程序,特别是这个函数:

/* Execute a command line. */
int
execute_line (line)
     char *line;
{
  register int i;
  COMMAND *command;
  char *word;

  /* Isolate the command word. */
  i = 0;
  while (line[i] && whitespace (line[i]))
    i++;
  word = line + i;

  while (line[i] && !whitespace (line[i]))
    i++;

  if (line[i])
    line[i++] = '\0';

  command = find_command (word);

  if (!command)
    {
      fprintf (stderr, "%s: No such command for FileMan.\n", word);
      return (-1);
    }

  /* Get argument to command, if any. */
  while (whitespace (line[i]))
    i++;

  word = line + i;

  /* Call the function. */
  return ((*(command->func)) (word));
}

我想了解如何以能够检查其元素的方式访问 char *word?例如 - 如果我想检查 char *word 的第一个元素是否为 '#' 并基于此执行某些逻辑,而不是当单词以其他任何开头时?我是 C 新手,发现我已经习惯了很多其他语言的东西;咳嗽蟒蛇;在 C 语言中本质上更难。

谢谢!

【问题讨论】:

  • 你的函数声明风格在 1990 年左右就已经过时了。你用什么作为参考?应该是int execute_line (lchar* line)(但这不是你的问题)
  • word[0] == '#' 怎么样?
  • 这与操作系统、gnu 或 readline 有什么关系?似乎是一个“我懒得阅读关于指针的章节的第 1 页”的问题......
  • John3136 如果您没有任何有用的东西要添加,为什么要添加任何东西?我已经尝试了很多方法,包括 OH MY GOD: word[0]。如果只是进行谷歌搜索,我不会在这里发帖。
  • @kensai01 你不认为指出标签垃圾邮件有用吗?一个(正确的)答案说明了您声称所做的事情。也许您需要更多关于实际问题的问题的详细信息?

标签: c readline


【解决方案1】:

天哪,那个古老的函数参数语法!

要检查指针数组的第一个元素,只需使用ptr_name[0],其中“ptr_name”是指针数组的名称/标识符。

如果您要查看特定字符是否为井号/井号。只需这样做:

if( word[0] == '#' ) // run code

【讨论】:

  • 感谢您的回复!我已经尝试过 word[0] 方法来访问元素,但这给了我一个分段错误(核心转储)错误。我还尝试从指针开始迭代字符数组并使用指针算法,但我仍然不知道如何访问第一个元素。我一定是错过了什么:(
【解决方案2】:

我能够用分词器解决这个问题。

/*Tokenizer, splits the arguments and detects presence of i/o or piping.*/
void Tokenize(char *sentence, char** StorageArray, char * delimiter)
{
    char *token;
    char *next_token;
    int counter = 1, position = 0;
    token = strtok(sentence, delimiter);
    next_token = token;
    while (next_token != NULL){
        TokenCount++;
        StorageArray[position] = token;

        /*Check for input / output markers*/
        if(strcmp(StorageArray[position], "<") == 0){ flagInput = 1;}
        if(strcmp(StorageArray[position], ">") == 0){ flagOutput = 1;}
        /*Check for pipeline instructions.*/
        if(strcmp(StorageArray[position], "|") == 0){ flagPipeInst = 1;}

        position++;
        if((next_token = strtok(NULL, delimiter))){
            token = next_token;
        }
        counter++;
    }
    counter--;
}

在将东西传递到执行命令之前,我得到了所有的令牌。

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多