我試圖了解下面的函式 *reverseString(const char *str) 如何使用指標算術反轉字串。我一直在谷歌搜索并觀看處理類似案件的視頻,但不幸的是他們沒有幫助我。您能否請有人幫助我了解此功能的作業原理可能缺少什么?我正在使用 Windows 10 專業版(64 位)和 Visual Studio Community 2019。提前感謝您一如既往的幫助。我很感激。
#include <iostream>
#include <cstring>
using namespace std;
char *reverseString(const char *str)
{
int len = strlen(str); // length = 10
char *result = new char[len 1]; // dynamically allocate memory for char[len 1] = 11
char *res = result len; // length of res = 11 10 = 21?
*res-- = '\0'; // subtracting ending null character from *res ?
while (*str)
*res-- = *str ; // swapping character?
return result; // why not res?
}
int main()
{
const char* str = "Constantin";
cout << reverseString(str) << endl;
}
uj5u.com熱心網友回復:
char *result = new char[len 1];
這一行分配一個新字串(另一個字串的字符長度,加上一個終止空值),并將其存盤在result. 注意result指向字串的開頭,并且不被修改。
char *res = result len;
這一行res指向result:的結尾res是一個指標,它等于 的地址result,但len后面的字符。
*res-- = '\0';
這一行:
- 將終止 NULL 寫入
res,當前指向 的結尾result,并且 - 遞減,
res以便它現在指向結果的前一個字符
while (*str)
*res-- = *str ; // swapping character?
這些線路:
- 回圈直到
str指向 NULL - 將 指向的字符寫入 指向
str的目標記憶體res,并且 res--:遞減res以指向記憶體中的前一個位置,并且str: 遞增str指向下一個字符str
return result; // why not res?
回傳結果是因為它指向新字串的(開頭)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/313902.html
上一篇:如何修復我的專案中的所有非空警告
