2017-12-21 43 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

「モーフ」はどこにポイントしていますか? – 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

関連する問題