C++指针→指针常见错误
其他
2018-09-30 09:04:11
阅读次数: 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;
int i = 5;
*p = i;
printf("%d\n", *p);
return 0;
}
|
- 原因如下:
- 变量的本质是内存中分配一段存储空间
- p由于没有指向,因此内部是个垃圾值,使用*p很可能访问了并没有给程序分配的存储空间
- 解决方法:提示:有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