を呼び出さずに関数から文字列を返すことは可能malloc
ですか? 私は以下のような機能を持っています:
char* getString(){
char tempStr[20]
// open file, read char by char and assign to tempStr
// ....
char* str = (char*)malloc(sizeof(char)*20);
strcpy(str, tempStr); // assume this copy the null terminating char as well
return str;
}
次に、 を呼び出すときにgetString()
、戻り値を に代入し、char*
完了したら解放します。次のようにします。
void randomFunction(){
char* line = NULL;
int i = 0;
while (i < 1000) {
line = getString();
// do stuff with line
free (line);
line = NULL;
}
}
ただし、なしでこれを行う方法があるかどうか疑問に思っていmalloc
ますか? そして、これは C 関数から文字列を返す適切な方法ですか? なしで戻る方法について調査を試みましたがmalloc
、明確な答えが見つかりませんでした。私はCが初めてで、まだ学んでいます。