指向結構體數組的指針


#include <iostream>
#include <string>
#include <windows.h>
using namespace std;

//定義一種類型
typedef struct MoreAndMore
{
    char name[66];//68
    int age;//4
    char *subname;//4
} mam;

//創建結構體指針
mam * creatStructArr(int a)
{
    int i = 0, j = 0;//定義遍歷數
    mam *arr = (mam *)malloc(3 * sizeof(mam));//分配一個大內存
    //遍歷輸入賦值結構體內容
    for (i = 0; i < 3; i++)
    {
        cout << "name:" << endl;
        cin >> arr[i].name;//輸入name
        cout << "age:" << endl;
        cin >> arr[i].age;//輸入age
        char *p = (char *)malloc(100 * sizeof(char));//分配一個小內存
        //遍歷初始化值
        for (j = 0; j < 100; j++)
        {
            p[j] = 0;
        }
        cout << "subname:" << endl;
        cin >> *p;//輸入subname
        arr[i].subname = p;//把內存指針掛在結構體上面
    }
    return arr;
}

//遍歷釋放結構體內部malloc的內存
void freeStruct(mam *p,int n)
{
    for (int i = 0; i < n; i++)
    {
        if ((p + i)->subname != NULL)
        {
            free((p + i)->subname);
        }
    }
}

//釋放內存
void freeS(mam *p)
{
    if (p != NULL)
    {
        free(p);
    }
}

//打印
void printStruct(mam *p, int n)
{
    int i = 0;
    for (i = 0; i < 3; i++)
    {
        cout << "name:" << (p+i)->name << endl;
        cout << "age:" << (p + i)->age << endl;
        cout << "subname:" << (p + i)->subname << endl;
    }
}
void main()
{
    /*mam xiao = { "axxa",NULL,21 };
    cout << sizeof(mam) << endl;*/
    int i = 0;//遍歷數
    int n = 3;//要自動生成的個數
    mam *p = creatStructArr(n);//開始生成 返回指針
    printStruct(p, n);//打印
    freeStruct(p, n);//釋放
    p = NULL;//避免野指針

    system("pause");
}

 


免責聲明!

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



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