文字列を逆にする必要があるのでしょうか、それとも出力だけを逆にする必要があるのでしょうか?
前者の場合、問題があります。宣言が本当なら
char *ch = "krishna is the best";
次に、文字列リテラルを変更しようとしており、文字列リテラルを変更しようとしたときの動作は未定義です。文字列リテラルが読み取り専用メモリに格納されているプラットフォームで作業している場合、実行時エラーが発生します。宣言を次のように変更する必要があります
char ch[] = "krishna is the best";
または動的バッファを割り当て、文字列の内容をそこにコピーします
char *ch = "krishna is the best";
char *buf = malloc(strlen(ch) + 1);
if (buf)
{
strcpy(buf, ch);
// reverse the contents of buf
}
その場で逆転を達成するために。
逆にする必要があるのが出力だけの場合、ストレージはそれほど重要ではありません。各部分文字列の最初と最後を追跡するために必要なのは、いくつかのポインターだけです。例えば:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *ch = "krishna is the best";
char *start, *end;
// point to the beginning of the string
start = ch;
// find the next space in the string
end = strchr(start, ' ');
// while there are more spaces in the string
while (end != NULL)
{
// set up a temporary pointer, starting at the space following the
// current word
char *p = end;
// while aren't at the beginning of the current word, decrement the
// pointer and print the character it points to
while (p-- != start)
putchar(*p);
putchar(' ');
// find the next space character, starting at the character
// following the previous space character.
start = end + 1;
end = strchr(start, ' ');
}
// We didn't find another space character, meaning we're at the start of
// the last word in the string. We find the end by adding the length of the
// last word to the start pointer.
end = start + strlen(start);
// Work our way back to the start of the word, printing
// each character.
while (end-- != start)
putchar(*end);
putchar('\n');
fflush(stdout);
return 0;
}
おそらくそれを行うためのより良い方法があります。これは私の頭の上からです。