책 연습문제 16장 5번
Posted: Thu Dec 15, 2016 6:34 pm
이 코드에서 *pt를 선언해서 길이에 맞게 재할당한 후에 ps에 연결에 연결하는 것으로 나와있는데, *pt를 선언안하고 ps를 동적 할당 후에 바로 ps를 길이에 맞게 재할당해서 풀면 안되나요? 굳이 *pt를 선언할 필요가 있나요?
Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char temp[32];
char *ps, *pt;
int len = 1;
ps = (char *)calloc(1, 1);
while (1)
{
printf("메모 입력 : ");
fgets(temp, sizeof(temp), stdin);
temp[strlen(temp) - 1] = '\0';
if (strcmp(temp, "end") == 0) break;
len += strlen(temp) + 1;
pt = (char*)realloc(ps, len);
if (pt == NULL)
{
printf("메모리 부족...\n");
break;
}
ps = pt;
strcat(ps, temp);
strcat(ps, " ");
}
printf("%s\n", ps);
free(ps);
return 0;
}