C++指针→指针常见错误

  1. 下面的程序会发生崩溃:
    1.  1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      #include <stdio.h>
      #include <iostream>
      
      using namespace std;
      
      int main(void)
      {
          int *p;
          int i = 5;
      
          *p = i;
          printf("%d\n", *p);
      
          return 0;
      }
  2. 原因如下:
    1. 变量的本质是内存中分配一段存储空间
    2. p由于没有指向,因此内部是个垃圾值,使用*p很可能访问了并没有给程序分配的存储空间
  3. 解决方法:提示:有2种

指针指向静态内存 指针指向动态内存
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <stdio.h>
#include <iostream>

using namespace std;

int main(void)
{
    int *p;
    int i = 5;

    p = &i;
    printf("%d\n", *p);

    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <stdio.h>
#include <iostream>

using namespace std;

int main(void)
{
    int *p = new int;
    int i = 5;

    *p = i;
    printf("%d\n", *p);

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/LeisureZhao/p/9727424.html