在C语言中,一个字符能否同时是换行符和空字符终止符?

3
  1. 以下代码片段中的if (cmdline[-1] == '\n' && cmdline[-1] == '\0')的目的是什么?
    • 在什么情况下会评估为真?
  2. cmdline[-1]中的负数索引在这里如何工作?我曾在SO上看到类似的问题,但在这里之前没有指针算术。

以下是该代码的伪代码:

parseInfo *parse (char *cmdline) {
  parseInfo *Result;
  char command[MAXLINE];
  int com_pos = -1;

  if (cmdline[-1] == '\n' && cmdline[-1] == '\0')
    return NULL;

  Result = malloc(sizeof(parseInfo));
  init_info(Result);
  com_pos=0;
  /*  while (cmdline[i] != '\n' && cmdline[i] != '\0') { */

  command[com_pos]='\0';
  parse_command(command, 0); /* &Result->CommArray[Result->pipeNum]);*/

  return Result;
}

编辑 #1: 为什么在以下情况下会打印出"When does this NOT get printed?": 编辑 #2: 我通过将长度增加1(包括空字符)并将length个字节复制到分配的length个字节中,使cmdline成为有效字符串。

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

void parse(char *cmdline) {
  printf("'%c'\n", cmdline[-1]);
  if (cmdline[-1] == '\0' || cmdline[-1] == '\n') {
    printf("When does this NOT get printed?\n");
  }
}

int main() {
  char str[100] = "hello";
  const int length = strlen(str) + 1;
  char *cmdline = malloc(length * sizeof(char));
  strncpy(cmdline, str, length);
  parse(cmdline);
  return 0;
}

相应的输出如下:

$ gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix
$ gcc negative_index.c
$ ./a.out
''
When does this NOT get printed?

1
cmdline[-1] == '\n' && cmdline[-1] == '\0' 总是为假。 - BLUEPIXY
6
我想这里应该用的是“||”,而不是“&&”? - João Vitor Verona Biazibetti
1
你最好考虑一下负数数组索引会产生什么影响。(提示:数组索引通常是 size_t,它通常与 unsigned long 相同,那么 -1unsigned long 中是多少?) - Some programmer dude
1
@JoachimPileborg cmdline[-1]*((cmdline)+(-1)) 是相同的。如果这不是良好定义的,那么你怎么能从指针中减去一个值呢?-- 操作符也会产生未定义行为吗? - Potatoswatter
1
NULL 是一个空指针常量。而空字符 '\0' 则是另一回事。 - Keith Thompson
显示剩余7条评论
1个回答

4
  1. No, a char can NOT be both \n and \0, the code perhaps meant to use || instead of &&.
  2. For example:

    char str[100] = "hello world";
    char *cmdline = str + 10;
    

    Then cmdline[-1] is the same as str[9].


我同意第一点,但这不是第二点所设置的cmdline。请查看我的问题编辑以获得澄清。 - rgardner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接