2014-04-01 2 views
0

사용자가 문자열을 입력 한 다음 대체하려는 문자를 입력하려는 경우 프로그램을 만들려고합니다. malloc을 사용하여 배열을 설정하고 싶지만 scanf를 사용하면 어떻게됩니까?사용자 입력이있는 malloc

누군가 도와 드릴 수 있습니다.

감사합니다.

이 프로그램이 대체 방법에 가기 전에 모습입니다 :

char *s,x,y; 

printf("Please enter String \n"); 
scanf("%s ", malloc(s)); 

printf("Please enter the character you want to replace\n"); 
scanf("%c ", &x); 

printf("Please enter replacment \n"); 
scanf("%c ", &y); 

prinf("%s",s); 
+1

(C99 표준의 일부가 아닌) POSIX ['getline()'] (http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html)이 필요하다고 생각합니다. – pmg

+0

당신의 malloc 사용은 끔찍한 잘못입니다. Malloc은 바이트 수를 취하여 포인터를 반환합니다. 포인터를 전달합니다. –

답변

0
scanf("%s ", malloc(s)); 

이 무엇을 의미합니까? 초기화되지 않은 포인터는 포인터입니다. 어떤 값이라도 가질 수 있습니다 (예 : 0x54654). 정의되지 않은 동작입니다. 당신이 사용자 입력이 아직 종료되지 않은 경우 동적으로 메모리를 할당해야하므로 코드가 있어야한다

,

int size_of_intput = 100; //decide size of string 
s = malloc(size_of_intput); 
scanf("%s ", s); 
+2

__always__ 버퍼 오버플로가 발생하지 않도록해야합니다. A> = 100 자의 사용자 입력은 코드로 힙 손상을 일으킬 수 있습니다. 대신'scanf ("% 99s", s)'를 전달하고 scanf의 반환 값을 확인하십시오. –

+0

@mic_e 훌륭한 조언. '% 99s '을 알지 못합니다. –

0

당신은 사전에 사용자 입력의 크기를 알 수 없다.

예제는 다음과 같습니다

//don't forget to free() the result when done! 
char *read_with_alloc(FILE *f) { 
    size_t bufsize = 8; 
    char *buf = (char *) malloc(bufsize); 
    size_t pos = 0; 

    while (1) { 
     int c = fgetc(f); 

     //read until EOF, 0 or newline is read 
     if (c < 0 or c == '\0' or c == '\n') { 
      buf[pos] = '\0'; 
      return buf; 
     } 

     buf[pos++] = (char) c; 

     //enlarge buf to hold whole string 
     if (pos == bufsize) { 
      bufsize *= 2; 
      buf = (char *) realloc((void *) buf, bufsize); 
     } 
    } 
} 

실용적인 대안 솔루션 (256 자, 예를 들어)를 버피의 크기를 제한하는 것, 그리고 바이트의 해당 번호를 읽어되어 있는지 확인 :

char buf[256]; //alternative: char *buf = malloc(256), make sure you understand the precise difference between these two! 
if (scanf("%255s", buf) != 1) { 
    //something went wrong! your error handling here. 
} 
관련 문제