c - 在C中使用指針,當反轉字元串時,如何獲得正確的輸出

  显示原文与译文双语对照的内容

我試圖用指針反轉C中的字元串,但是輸出真的很奇怪,邏輯很好,但我不確定它為什麼會這樣輸出,下面是代碼:


#include <stdio.h>


#include <string.h>



int main()


{


 char str[20], reverse_str[20], *pointer;


 int i = 0;



 printf("%s","Enter any string:");


 scanf("%s", str);


 pointer = str;



 int string_length = strlen(pointer);



 //int count = 0;


 for (int i = string_length; i > 0; i--){


 reverse_str[i -1] = *pointer;


 pointer++;


 }


 printf("%dn", string_length);


 printf("Original string = %sn", str);


 printf("Reversed string = %sn", reverse_str);



}



輸出如下所示:


Enter any string: Hello



Original string = Hello


Reversed string = olleH╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Hello



时间:

我試圖用指針反轉C中的字元串,但是輸出真的很奇怪,邏輯很好,但我不確定它為什麼會這樣輸出,下面是代碼:


#include <stdio.h>


#include <string.h>



int main()


{


 char str[20], reverse_str[20], *pointer;


 int i = 0;



 printf("%s","Enter any string:");


 scanf("%s", str);


 pointer = str;



 int string_length = strlen(pointer);



 //int count = 0;


 for (int i = string_length; i > 0; i--){


 reverse_str[i -1] = *pointer;


 pointer++;


 }


 printf("%dn", string_length);


 printf("Original string = %sn", str);


 printf("Reversed string = %sn", reverse_str);



}



輸出如下所示:


Enter any string: Hello



Original string = Hello


Reversed string = olleH╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Hello



我試圖用指針反轉C中的字元串,但是輸出真的很奇怪,邏輯很好,但我不確定它為什麼會這樣輸出,下面是代碼:


#include <stdio.h>


#include <string.h>



int main()


{


 char str[20], reverse_str[20], *pointer;


 int i = 0;



 printf("%s","Enter any string:");


 scanf("%s", str);


 pointer = str;



 int string_length = strlen(pointer);



 //int count = 0;


 for (int i = string_length; i > 0; i--){


 reverse_str[i -1] = *pointer;


 pointer++;


 }


 printf("%dn", string_length);


 printf("Original string = %sn", str);


 printf("Reversed string = %sn", reverse_str);



}



輸出如下所示:


Enter any string: Hello



Original string = Hello


Reversed string = olleH╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Hello



...