有人可以解释为什么指针没有初始化NULL?
例:
void test(){
char *buf;
if (!buf)
// whatever
}
Run Code Online (Sandbox Code Playgroud)
程序不会进入if,因为buf它不是null.
我想知道为什么,在什么情况下我们需要一个带垃圾的变量,特别是指针解决内存上的垃圾问题?
我正在搞乱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);
}
Run Code Online (Sandbox Code Playgroud)
我得到输出:
ptr is not NULL
ptr value is 1
ptr address is 0x7fff801ace30
Run Code Online (Sandbox Code Playgroud)
如果我没有为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"); …Run Code Online (Sandbox Code Playgroud)