在C语言中,指针的地址可以为0吗? [英] In C, can an address of a pointer be 0?

查看:1412
本文介绍了在C语言中,指针的地址可以为0吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读破解编码面试书(问题1.2)中的问题解决方案.那里的目标是在C中实现一个功能void revers(char* str),该功能可以反转空终止字符串.

I'm reading the solution to a problem in the book Cracking the Coding interview (Q 1.2). The objective there is to implement a function void revers(char* str) in C that reverses a null terminating string.

解决方案代码如下:

void reverse(char *str)
{
   char* end=str;
   char tmp;
   if(str)
   {
       while(*end)
       {
          end++;
       }
       end--;
       //code to reverse
   }
}

在这里,str包含地址,对吗?并且if(str)仅在str0时才评估为false,对吗?

Here, str contains an address right? And if(str) will only evaluate to false if str is 0, right?

所以我的意思是,str不会包含地址0x0000,从而将if(str)评估为false吗?

So what I'm saying is, is there no chance that str will contain the address 0x0000, thus evaluating if(str) to false?

推荐答案

str确实包含一个地址(它是指向char的指针),并且if(str)如果等于空指针.

str does indeed contain an address (it's a pointer to char), and if(str) will evaluate to false iff the str is equal to the null pointer.

请注意,标准不要求使用空指针来引用地址0;但是,该标准要求在编译器上下文中使用0文字值时,编译器必须将其解释为空指针的地址-不管是什么.

Note that the null pointer is not required by the standard to refer to address 0; however, the standard mandates that a literal value of 0 when used in a pointer context must be interpreted by the compiler as the address of the null pointer -- whatever that might be.

这意味着保证测试if(p == 0)始终与if(p == NULL)相同.另外,保证条件if(p)始终与if(p != 0)相同.

This means that the test if(p == 0) is guaranteed to always be the same as if(p == NULL). Also, the conditional if(p) is guaranteed to always be the same as if(p != 0).

结论:您的代码将始终检测到一个空指针,但是在技术上与指向地址零的指针并不相同(即使在实践中您通常会发现它是)

Conclusion: your code will always detect a null pointer, but that's not technically the same as a pointer that points to address zero (even though in practice you are going to find that it usually is).

这篇关于在C语言中,指针的地址可以为0吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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