【发布时间】:2016-05-18 18:21:08
【问题描述】:
我在搞乱 C 指针。当我编译并运行以下代码时。
示例 1:
#include <stdio.h>
int main()
{
int k;
int *ptr;
k = 555;
if (ptr == NULL) {
printf("ptr is NULL\n");
} else {
printf("ptr is not NULL\n");
printf("ptr value is %d\n", *ptr);
}
printf("ptr address is %p\n", ptr);
}
我得到了输出:
ptr is not NULL
ptr value is 1
ptr address is 0x7fff801ace30
如果我不给 k 赋值:
示例 2:
#include <stdio.h>
int main()
{
int k;
int *ptr;
if (ptr == NULL) {
printf("ptr is NULL\n");
} else {
printf("ptr is not NULL\n");
printf("ptr value is %d\n", *ptr);
}
printf("ptr address is %p\n", ptr);
}
那么输出如我所料:
ptr is NULL
ptr address is (nil)
同样,如果我在函数之外定义变量:
示例 3:
#include <stdio.h>
int k;
int *ptr;
int main()
{
k = 555;
if (ptr == NULL) {
printf("ptr is NULL\n");
} else {
printf("ptr is not NULL\n");
printf("ptr value is %d\n", *ptr);
}
printf("ptr address is %p\n", ptr);
}
输出:
ptr is NULL
ptr address is (nil)
在第一个例子中,ptr 有一个地址和值,这是预期的行为吗?如果是的话:
- 为什么 ptr 有地址和值?
- 这些来自哪里,是什么原因造成的?
- 如何在本地范围内正确定义空指针并保持它们为空,直到我准备好使用?
我在 x64 上的 Ubuntu 12.04.04 上使用 gcc 进行编译:
root@dev:~# gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.6/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.6.3-1ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.6/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.6 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.6 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
编辑
为清楚起见,我在上面的示例中进行了编号。
根据 Dietrich 的回答,我进行了一些搜索,发现了这个问题:Why are global variables always initialized to '0', but not local variables?。
【问题讨论】:
标签: c pointers null variable-assignment