I am basically trying to de-allocate memory from a structure which had user inputted data, so the goal is to wipe the data so a new set of data can be re entered into the structure.
This is the structure
struct packet{
int source;
int destination;
int type; // Varibles for the structure
int port;
char data[50];
char * filename;
};
pointers to the structure
struct packet s[50]; //Array for structure input
struct packet *p_s;
p_s = malloc(sizeof(struct packet));
the code where user inputted data is added to the variables in the structure
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);
This is how I view the structure 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);
Finally code I would like help with in terms of getting it to remove the set of user inputed data from above so a new set can be added.
system("cls");
free(p_s);
printf("All the data entered has been cleared. Press any key to continue");
You only need free(p_s);
. You cannot deallocate the members one-by-one since they weren't allocated one-by-one either.
If you want to re-use the previous allocated memory. You can use memset to fill all allocated memory to '\\0'. By doing this you are reseting the whole strcuture except the char* filename! This char* you need to allocate, and dellocate independent of allocating or dellocating the parent structure.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.