아래의 코드는 기본적으로 작동이 되지 않는다. 왜일까? 그것은 바로 포인터에 있다. 배열의 경우에는 배열 이름 자체가 포인터. 메모리 주소 값이기 때문에 전달할 경우 정상적으로 처리가 되나 여기서는 포인터를 넘겨주는 것 '처럼'보이지만 실제로는 쓰레기값을 넘겨준다. 그러므로 포인터를 인자로 넘기고 함수에서 다루기 위해선 포인터의 주소를 넘겨 포인터 그 자체를 다루어야 한다. 즉 이중 포인터를 사용해서 해결
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void input_a_word(char *);
int main(void){
char *word;
input_a_word(word);
printf("%s\n",word);
free(word);
return 0;
}
void input_a_word(char *input){
char temp[100];
int word_size = 0;
char c;
while(1){
c = getchar();
if(c == '\n')
break;
temp[word_size] = c;
word_size++;
}
temp[word_size] = '\0';
printf("%s\n", temp);
input = (char *)calloc(strlen(temp)+1, sizeof(char));
strcpy(input, temp);
}