如何检查char *变量是否指向空字符串? [英] How can I check if char* variable points to empty string?

查看:248
本文介绍了如何检查char *变量是否指向空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查char*变量是否指向空字符串?

How can I check if char* variable points to an empty string?

推荐答案

检查第一个字符是否为'\ 0'.您还应该检查指针是否为NULL.

Check if the first character is '\0'. You should also probably check if your pointer is NULL.

char *c = "";
if ((c != NULL) && (c[0] == '\0')) {
   printf("c is empty\n");
}

您可以将这两个检查都放在一个函数中,以使其方便且易于重用.

You could put both of those checks in a function to make it convenient and easy to reuse.

在if语句中可以这样读取:如果c不为零,并且字符数组'c'的第一个字符不为'\ 0'或零,则...".

In the if statement can be read like this, "If c is not zero and the first character of character array 'c' is not '\0' or zero, then...".

&&仅将两个条件组合在一起.基本上就像这样说:

The && simply combines the two conditions. It is basically like saying this:

if (c != NULL) { /* AND (or &&) */
    if (c[0] == '\0') {
        printf("c is empty\n");
    }
}

如果您还不清楚,那么您可能想获得一本不错的C编程书.我可以推荐一本书,叫做《 The C Programming Language》.

You may want to get a good C programming book if that is not clear to you. I could recommend a book called "The C Programming Language".

与上述等效的最短版本是:

The shortest version equivalent to the above would be:

if (c && !c[0]) {
  printf("c is empty\n");
}

这篇关于如何检查char *变量是否指向空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆