C/C++ 錯誤筆記-在給結構體中的指針賦值時,要注意該指針是否已指向內存空間


先來看下面的例子:

#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了。因此在使用指針時需要記得一句話:

沒有內存,哪來的指針? 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM