malloc了多個結構體長度的內存後,怎樣操作每個結構體


#include<stdio.h>  
#include<string>
#include<iostream>
#include <stdlib.h>
using namespace std;
typedef struct tagtest
{
	int ID;
	char name[24];
}TEST;

int main()
{
	int num = 10;
	int ulmemsize = sizeof(TEST) * num;
	TEST *pstrfid = static_cast<TEST>(malloc(ulmemsize));
	if(NULL == pstrfid)
    {	
		return 0;
	}
	menset(pstrfid, 0);
	for(int i = 0; i < num; ++i)
	{
		pstrfid[i].ID = i;//或者這樣也可以:(pstrfid + i)->ID。下標[]指的是結構體本身,+ 指的是指向第i個結構體的指針
		pstrfid[i].name = "cyc";
	}
	
	TEST *psttmp = &(pstrfid[5]);
	cout << psttmp->ID << psttmp->name << endl;
	free(pstrfid);
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章