为什么声明指针会使其内容为零?
可能的重复:
已声明但未设置的变量计算结果为 true?
为什么此代码适用于Mac OS
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *str;
NSLog(@"%@", [str length]);
NSLog(@"Hello, World!");
[pool drain];
return 0;
}
和控制台输出
2011-09-23 15:37:17.481 Untitled1[80021:903] (null)
2011-09-23 15:37:17.495 Untitled1[80021:903] Hello, World!
在 iPhone 上却崩溃了?
Possible Duplicate:
Declared but unset variable evaluates as true?
Why does this code work on Mac OS
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *str;
NSLog(@"%@", [str length]);
NSLog(@"Hello, World!");
[pool drain];
return 0;
}
and console output is
2011-09-23 15:37:17.481 Untitled1[80021:903] (null)
2011-09-23 15:37:17.495 Untitled1[80021:903] Hello, World!
but crashes on iPhone ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你只是幸运而已。局部变量未初始化,可以包含任何内容。在 OS X 上,str 很可能包含 0(也称为 nil),将
-length
发送到 nil 返回 0。然后您将长度(它是一个NSInteger
)视为NSLog 的指针。如果长度为 0,且格式说明符为
%@
,NSLog
会将其视为 nil 指针,并打印(null)
。如果
str
有一个随机的非零值,那么当您发送长度时,您的程序将崩溃,或者如果它奇迹般地工作并返回非零长度,则在尝试将其视为对象指针时可能会崩溃在 NSLog 中You were just lucky. Local variables are uninitialised and could contain anything. It's likely that on OS X, str contains 0 (aka nil), sending
-length
to nil returns 0. Then you are treating the length (which is anNSInteger
) as a pointer for theNSLog
.If the length is 0, the
NSLog
will treat it as a nil pointer if the format specifier is%@
and will print(null)
.If
str
has a random non zero value, either your program will crash when you send length or if it miraculously works and returns a non zero length, it'll probably crash trying to treat it as an object pointer in NSLog该值从未被初始化(或设置)。它可以是任何随机值。在调试时,它可能被零初始化。
在这种情况下,您应该预料到会发生崩溃(或某些 UB)。所以...打开编译器和静态分析器警告,解决问题,并始终初始化您的值。
the value is never initialized (or set). it could be any random value. in debug, it may be zero-iniitalized.
a crash (or some UB) is what you should expect in this case. so... turn up your compiler and static analyzer warnings, fix the issues, and always initialize your values.
试试这个。
try this.
看 ,
您只能对 nil 对象调用release方法。除了release方法之外,我们不能通过nil调用任何方法。
这里你正在一个指向 nil 的对象上调用一个方法(length),在这种情况下,在发送 length 消息之前它通常应该指向 nsstring 对象。
See ,
You can call only release method over a nil object. other than release method we cannot call any method over a nil.
Here you are calling a method ( length )over an object which is pointing to nil , in this case it should point to nsstring object in general before sending length message .
两个错误。
首先,声明指针 str,不要设置它的值并在 NSLog 中使用它。
其次,您使用格式%@,但提供整数值([str length]),结果未定义。这就是为什么在模拟器上它打印 null,但在设备上崩溃。
Two mistakes.
First, you declare pointer str, don't set it's value and use it in NSLog.
Second, you use formatting %@, but supply integer value ([str length]), result is undefined. That's why on simulator it prints null, but crashes on device.