2013-12-18 2 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); 

이것은 어떻게 구조의 변수에 추가되는 코드 구조 데이터보기

마지막으로 코드 위에서 입력 한 사용자 입력 데이터를 제거하여 새로운 세트를 추가 할 수 있도록 도움을 드리고 싶습니다.

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 *는 부모 구조를 할당하거나 dellocating하는 것과 독립적으로 할당하고 할당해야합니다.

+1

이 문제의 예제로 어떻게 넣을 수 있습니까? memset 사용 방법을 모르겠다 –

+0

확실! memset을 사용하면 버퍼의 모든 바이트를 특정 값으로 설정할 수 있습니다. '
#define BUFFER_LEN 128
char 버퍼 [BUFFER_LEN];

...
memset (버퍼, '\ 0', BUFFER_LEN); ' ' –