我基本上試圖從具有用戶輸入數據的結構中取消分配內存,因此目標是擦除數據,以便可以將新數據集重新輸入到結構中。從結構中釋放內存
這是結構
struct packet{
int source;
int destination;
int type; // Varibles for the structure
int port;
char data[50];
char * filename;
};
指針結構
struct packet s[50]; //Array for structure input
struct packet *p_s;
p_s = malloc(sizeof(struct packet));
其中用戶輸入的數據被添加到變量在結構
printf("\n****Adding a packet*****\n");
printf("Where is the packet from?\n");
scanf("%i", &s[NetworkPacket].source);
printf("Where is the packet going?\n");
scanf("%i", &s[NetworkPacket].destination);
printf("What type is the packet?\n");
scanf("%i", &s[NetworkPacket].type); // collecting the data of the packet inputted by the user
printf("What is the packet's port?\n");
scanf("%i", &s[NetworkPacket].port);
printf("Enter up to 50 characters of data.\n");
scanf("%s", s[NetworkPacket].data);
這是怎樣的代碼我查看結構數據
printf("\n%i\nSource: %d", ii, s[ii].source);
printf("\nDestination: %d", s[ii].destination);
printf("\nType : %d", s[ii].type);// if statement giving the limit of 50 packets allowed to be added
printf("\nPort : %d", s[ii].port);
printf("\nData: %s\n---\n", s[ii].data);
最後的代碼我希望能幫助它從上面刪除一組用戶輸入的數據,這樣就可以添加一個新的集合。
system("cls");
free(p_s);
printf("All the data entered has been cleared. Press any key to continue");
一般來說,你只需要在''malloc''之前使用'free'。 – dreamlax
你只需要釋放你擁有malloc的struct成員。 – moeCake