相关疑难解决方法(0)

为什么默认情况下没有使用NULL初始化指针?

有人可以解释为什么指针没有初始化NULL
例:

  void test(){
     char *buf;
     if (!buf)
        // whatever
  }
Run Code Online (Sandbox Code Playgroud)

程序不会进入if,因为buf它不是null.

我想知道为什么,在什么情况下我们需要一个带垃圾的变量,特别是指针解决内存上的垃圾问题?

c++ memory pointers initialization

117
推荐指数
7
解决办法
7万
查看次数

未设置的C指针不为空

我正在搞乱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)

c null pointers variable-assignment

2
推荐指数
1
解决办法
1361
查看次数

标签 统计

pointers ×2

c ×1

c++ ×1

initialization ×1

memory ×1

null ×1

variable-assignment ×1