2013-12-18 67 views
0

我基本上试图从具有用户输入数据的结构中取消分配内存,因此目标是擦除数据,以便可以将新数据集重新输入到结构中。从结构中释放内存

这是结构

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"); 
+3

一般来说,你只需要在''malloc''之前使用'free'。 – dreamlax

+0

你只需要释放你拥有malloc的struct成员。 – moeCake

回答

1

您只需要free(p_s);。您不能一个接一个地分配成员,因为他们也不是一一分配的。

+0

我试过了,记录仍然存在,当我查看它们时 –

+0

@NabilAziz:你是如何查看它们的? – dreamlax

+0

我发布了一个更新,显示 –

1

如果您想重新使用先前分配的内存。您可以使用memset将所有分配的内存填充到'\ 0'。通过这样做,您正在重设除char *文件名外的整个strcuture!您需要分配此char *,并独立于分配或取消分配父结构而取消分配。

+1

你能告诉我我将如何把这个问题作为一个例子吗?不知道如何使用memset –

+0

当然!使用memset,您可以将缓冲区的所有字节设置为特定值。 '
#define BUFFER_LEN 128
char buffer [BUFFER_LEN]; (缓冲区,'\ 0',BUFFER_LEN);' ' –