テキストを大文字に変換するプログラムを作りました。コンパイルはできたのですが、実行してみると期待どおりの結果になりません。
![](/wp-content/include/images/avatar/teacher/5.png)
何が間違っているか分かりますか?
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
const char *ToUpperText(const char *pText) {
size_t length = strlen(pText);
char UpperText[length + 1];
for (int i=0; i<length; i++) {
UpperText[i] = toupper(pText[i]);
}
UpperText[length] = '\0';
return UpperText;
}
int main(void) {
char text[] = "The C Programming Language";
puts(text);
puts(ToUpperText(text));
return EXIT_SUCCESS;
}
期待される実行結果
The C Programming Language
THE C PROGRAMMING LANGUAGE
![](/wp-content/include/images/avatar/student/2.png)
このプログラムを実行すると、表示がおかしくなるってことですか?
![](/wp-content/include/images/avatar/teacher/10.png)
そうね。最悪の場合は、クラッシュしてしまうかも。
![](/wp-content/include/images/avatar/student/6.png)
じゃあ、クラッシュしないプログラムに直せばいいんですね。
![](/wp-content/include/images/avatar/teacher/4.png)
そういうことよ。
![](/wp-content/include/images/avatar/student/7.png)
えっと、怪しいのはこの関数かな……
const char *ToUpperText(const char *pText) {
……
}
![](/wp-content/include/images/avatar/student/3.png)
関数名が
ToUpperText()
だから、これがテキストを大文字に変換する関数ですね。
![](/wp-content/include/images/avatar/teacher/13.png)
そうそう。引数で受け取った文字列を、大文字の文字列に変換して返す仕様になってるわね。
![](/wp-content/include/images/avatar/student/7.png)
関数の中身は……
for (int i=0; i<length; i++) {
UpperText[i] = toupper(pText[i]);
}
UpperText[length] = '\0';
![](/wp-content/include/images/avatar/student/8.png)
ふむふむ。
for
ループで1文字ずつ大文字に変換して、最後に'\0'
を付けてるんですね。
![](/wp-content/include/images/avatar/teacher/3.png)
'\0'
は、第17問でも出てきた「ヌル文字」ね。
![](/wp-content/include/images/avatar/student/11.png)
ですね!……あれ?このループはとくに問題なさそうですよ。
![](/wp-content/include/images/avatar/teacher/9.png)
ふふふ。それじゃあ、問題があるのはどの部分かしらね。
![](/wp-content/include/images/avatar/teacher/7.png)
実際にコンパイルしてみれば分かるかも?