先來看下面的例子:
#include <stdlib.h> #include <string.h> #include <stdio.h> #pragma warning(disable:4996) typedef struct _Student { char name[64]; int age; }Student; typedef struct _Teacher { char name[64]; int age; char *p1; char **p2; Student s1; Student *ps1; }Teacher; int main() { Teacher t1; t1.age = 30; t1.s1.age = 20; // 操作結構體中的結構體指針 t1.ps1->age = 100; system("pause"); return 0; }
編譯,沒有問題,但是一運行,程序直接報錯
問題出現在
t1.ps1->age = 100; 這一行,因為我們在給結構體指針Student的age屬性賦值時,並未給ps1指針開辟內存空間,所以相當於給一個空指針賦值,因此程序crash掉了。
下面是修改后的代碼:
int main() { Teacher t1; Student s1; t1.age = 30; t1.s1.age = 20; // 操作結構體中的結構體指針 t1.ps1 = &s1; t1.ps1->age = 100; system("pause"); return 0; }
我們在給ps1的age屬性賦值時,已為ps1指向了一塊內存空間,這樣程序就不會再crach了。因此在使用指針時需要記得一句話: