2017-12-21 26 views
-4

문제가 무엇인지 잘 모르겠습니다. 이 함수는 잘 작동하는 것 같지만, 주 함수에서 printf으로 테스트 할 때 결과를 표시하지 않습니다.함수에서 C로 소문자로 만들기

char* MotMiniscule(char* mot) 
{ 
char motm[100],c,*motf; 
int i=0; 
strcpy(motm,mot); 
c=motm[i]; 
while(c!='\0') 
{ 
    printf("%c \n",c); 
    motm[i]=tolower(c); 
    i++; 
    c=motm[i]; 
} 
strcpy(motf,motm); 
printf("%s\n",motf); 
return(motf); 
} 

main() 
{ 
char *mot="HEllooOoMA",*min; 
min=MotMiniscule(mot); 
printf("\n le mot est %s:\n",mot); 
printf("|| %s ||",min); 
} 

Image

+3

'motf'는 어디로 가리 킵니까? – iBug

+1

'motf'는 초기화되지 않은 포인터입니다. –

+2

필요하지 않으면 이미지를 게시하지 마십시오. 텍스트로 게시하십시오. – klutt

답변

2

당신은 기능 MotMiniscule에 포인터 motf을위한 공간을 할당 적이 : 이것은 정의되지 않은 동작이

strcpy(motf,motm); 

motf의 주소는 불확정이기 때문이다.

motf = malloc(100); 

는 전체 코드가 있어야한다 : 당신은 그것을 가리 키도록 일부 공간을 제공한다

char* MotMiniscule(char* mot) 
{ 
    char motm[100],c,*motf; 
    int i=0; 
    strcpy(motm,mot); 
    c=motm[i]; 
    while(c!='\0') 
    { 
     printf("%c \n",c); 
     motm[i]=tolower(c); 
     i++; 
     c=motm[i]; 
    } 
    motf = malloc(100); // Allocate some memory 
    strcpy(motf,motm); 
    printf("%s\n",motf); 
    return(motf); 
} 

int main() 
{ 
    char *mot="HEllooOoMA",*min; 
    min=MotMiniscule(mot); 
    printf("\n le mot est %s:\n",mot); 
    printf("|| %s ||",min); 
    free(min); // Don't forget to free dynamically allocated memory 
} 

으로 존 보데 지적을 motm의 사용은 완전히 중복됩니다. 안전하게 제거 할 수 있습니다. 게다가, 동적 할당의 크기는 mod의 길이에 의존해야합니다. 코드의 세련된 버전이 바로 이것입니다.

char* MotMiniscule(char* mot) 
{ 
    char c, *motf; 
    int i = 0; 
    c = mot[0]; 
    motf = malloc(strlen(mot) + 1); // Allocate some memory 
    while (c != '\0') 
    { 
     printf("%c\n", c); 
     motf[i] = tolower(c); 
     i++; 
     c = mot[i]; 
    } 
    // No need to copy again, but 
    motf[i] = '\0'; // Remember to terminate it 
    printf("%s\n", motf); 
    return(motf); 
} 

int main() 
{ 
    char *mot = "HEllooOoMA", *min; 
    min = MotMiniscule(mot); 
    printf("\n le mot est %s:\n", mot); 
    printf("|| %s ||", min); 
    free(min); // Remember to free it 
} 
+0

그리고 메모리를 할당 해제하기 위해'main()'의 끝에서'free (min);'를 호출하십시오. 프로그램은 그 시점에서 끝나고 모든 현대 플랫폼에서 프로세스의 분해로 복구되지만'malloc()'을'free()'와 매치하지 않는 것은 나쁜 습관입니다. – Persixty

+1

Quibble - 'malloc'의 인수는 임의의 상수가 아닌 입력 문자열의 크기를 기반으로해야합니다. –

+1

@Persixty 나는 그것을 바로 추가했다 ...? – iBug