用指针写条件的几种方式的区别
Differences among several ways of writing conditions with pointers
我想知道是否有人可以总结一下写一个涉及指针的条件语句的方法之间的区别:
if(p)
if(p != 0)
if(p != NULL)
我经常对以下情况感到困惑(肯定有更多,请补充你的情况)何时使用which:
static char *p1;
char *p2 = new char();
const char *p3 = "hello"; /*then I repeatedly do p3++*/
char *p4 = 0;
char *p5 = NULL;
编辑
另外,我想知道,对于char *p
,我们是否有while(*p)
或while(*p!=0)
,可能相当于while(p)
或while(p!=0)
或while(p!=NULL)
或while(*p!=' ')
(或任何其他?)在while循环内的一些p++
之后?
if(p)
在此上下文中,p
被转换为bool
,这实际上与p != 0
相同。
if(p!=0)
这是检查空指针的显式方法,与上一个相同。
if(p != NULL)
与此不同的是NULL
是一个宏;在C中定义为(void*)0
,而在c++中定义为0
。同样,它的检查与前两个表达式相同。
基本上,它们都做同样的事情(除了NULL
宏没有被定义或被重新定义为其他东西)。我倾向于使用p != 0
,因为它与p
相同,但它是明确声明的。使用NULL
的版本需要包含stddef
或cstddef
,这通常不是问题。
在c++ 11中有一种新的方法来检查空指针:nullptr
,这是一个新的关键字。如果可用,这将是理想的选择,因为它清楚地说明p
是一个指针:
if( p != nullptr )
这些都是检查p
是否不是0
的方法;它们做同样的事情:
if(p) // Short and simple.
if(p != 0) // Easier to understand.
if(p != NULL) // POINTERS ONLY.
在c++ 11中,您可以使用这种"更安全"的方式来检查指针是否为NULL
:
if(p != nullptr)
当你想创建一个'动态分配'的char
s数组时,你可以这样做:
char *p2 = new char[4];
strcpy(p2, "abc");
// Don't forget to delete!
delete[] p2;
一个更好的选择是使用更安全的c++:
std::array<char, 256> p2 = {'b', 'b', 'c', 0};
p2[0] = 'a'; // "abc"
或:
std::string p2 = "bbc";
p2 = "abc";
p2[0] = 'c'; // "cbc"
将p3
设置为字符串"hello"
:
const char *p3 = "hello";
增加p3
在内存中指向的位置:
// *p3 = 'h';
p3++;
// *p3 = 'e';
p3++;
// *p3 = 'l';
p3++;
// *p3 = 'l';
要理解你为什么这样做:
char *p4 = 0;
char *p5 = NULL;
查看这个问题:在free
之后将变量设置为NULL我不会在c++中使用static char*
,但这里有一个愚蠢的例子:
void sc(char *first = NULL)
{
static char *p = NULL;
if(p == NULL)
p = &first;
// p will never change (even when sc() ends) unless you set it to NULL again:
// p = NULL;
}
char initial_value;
sc(&initial_value);
sc();
sc();
// ...
相关文章:
- 在C++中将函数压缩为两种方式
- 在C++中,如何通过几种类型从元组中选择多个元素
- 哪种方式更快?究竟发生了什么,我们没有看到什么?
- 将函数作为参数传递的两种方式之间的区别
- 如何在同一个模板功能上专门化几种类型?
- 初始化结构的两种方式
- 在 C 中并行化嵌套循环的几种方法之间的差异,C++使用 OpenMP
- !=的另一种方式
- Qt - 在没有正则表达式的情况下,将 QString 拆分为几种类型的空格
- 以一种方式使用字符串选择(如果语句)
- 这两种方式有什么区别吗?
- 在 OpenGL 中渲染对象的哪种方式更有效
- 在哪种方式搜索容器中的元素的方式更有效
- 从文件中读取未签名字符的几种不同方法
- C++阿特金的筛子返回了几种复合材料
- 最简单的方法来封装几个语句中的几种语句
- 一种方式链接列表和不需要的第一个元素AFRTER填充
- 由于您可以在C 中以两种方式声明复制构造函数,这是正确的方式
- 重载输入/输出运算符,为什么它以这种方式工作而不是以另一种方式工作
- 用指针写条件的几种方式的区别