Can a character in C be both a newline character and a NULL terminator?
- What is the purpose of
if (cmdline[-1] == '\n' && cmdline[-1] == '\0')
the following code example?- when will it ever be judged true?
- How does the negative index work here
cmdline[-1]
? I've seen similar questions on SO, but there is no pointer arithmetic in advance here.
Here's the pseudocode:
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;
}
EDIT # 1: Why "When is this NOT printed?" printed in the following situation: EDIT # 2: I made a cmdline
valid string by increasing the length by 1 (including the null character) and copying the length
bytes into length
malloc'd.
#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;
}
With the appropriate output:
$ 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?
+3
source to share