下麵的程式會發生崩潰: 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 = ...
- 下麵的程式會發生崩潰:
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; }