[C Programming] malloc과 fgets의 사용

kkt5116의 이미지

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
 
void memoryAlloc (int a);
 
int main(int argc, char* argv[])
{
	int choice;
	fputs("Please enter the maximum length of string: ",stdout);
	scanf("%d",&choice);
	memoryAlloc(choice);
 
	return 0;
}
 
void memoryAlloc (int a){
 
	char* arr;
 
	arr = (char*)malloc( a * sizeof(char));
	if (arr == NULL){
		fputs("Failed to allocate memory!!!",stdout);
		exit(1);
	}
 
	fputs("Please enter strings: ",stdout);
	fgets(arr,sizeof(arr),stdin); // scanf("%s",arr);
 
	printf("Entered strings: %s\n",arr);
 
	fflush(stdin); 
	free(arr);
}

안녕하세요. 이제 c프로그램에 막 입문한 노땅새내기에요 ㅡㅡㅋ
다름이 아니라 주석 처리한 부분에 문제가 생겨서 그런데요.
fgets()를 쓰면 입력 자체가 안되더라고요.
근데 scanf()를 쓰면 되구요. 왜 그런거죠?;;

ymir의 이미지

sizeof 는 datatype 의 크기를 리턴하고, 배열에 대해서만 배열의 크기를 리턴합니다.
sizeof(arr) 라면 결국 char pointer 의 크기만큼만 리턴하게 되겠죠.

http://en.wikipedia.org/wiki/Sizeof

되면 한다! / feel no sorrow, feel no pain, feel no hurt, there's nothing gained.. only love will then remain.. 『 Mizz 』

되면 한다! / feel no sorrow, feel no pain, feel no hurt, there's nothing gained.. only love will then remain.. 『 Mizz 』

kkt5116의 이미지

아 그렇군요!!! 감사합니다