我正在从scanf().
用户读取输入字符串
我想检查这个字符串是否为空(\0)。
这是我的代码:
#include<stdio.h>
char *argument; // argument for mycat
scanf("%s", &argument);
if(fork()==0) // at child
{
printf("Child process: about to execute \"mycat %s\"\n", &argument);
fflush(stdout);
if(strcmp(argument, "") == 0) // <-- Here is the problem
{
execlp("mycat", "mycat", &argument, NULL); // execute child process
}
execlp("mycat","mycat", NULL);
}
我用g++编译器在Red Hat 6.1上编译
编辑:问题是我不能对
argument
语句或甚至与if
一起使用的strlen()
取消引用。 最佳答案
NULL
和\0
不是一回事,尽管它们的值都为零。NULL
是指针0,也就是说,它是我们用来表示空指针的。\0
是ASCII数字为零的字符,也称为NUL
(一个“L”),即是值为0的char
。
achar *
是NULL
(即内存中根本没有字符串)或字符串是空的(即只包含一个char
,即\0
或者称为NUL
)之间有一个重要的区别。
要测试第一个:
if (!string)
或者如果你想更详细些:
if (string == NULL)
要测试第二个:
if (!string[0])
或者如果你想更详细些:
if (string[0] == 0)
显然,如果需要同时测试这两个指针,请先测试第一个,然后再测试第二个,因为如果
string
是NULL
,则第二个指针将取消引用空指针。