使用指针反转字符数组
Reverse char array using pointers
无法理解 while
中发生的事情 如果可能的话,请形象化。
int main()
{
char text[] = "hello";
int nChars = sizeof(text)-1;
char *pStart = text;
char *pEnd = text + nChars - 1;
//can't understand this part
while (pStart < pEnd)
{
char tmp = *pStart;
*pStart = *pEnd;
*pEnd = tmp;
pStart++;
pEnd--;
}
cout << text << endl;
return 0;
}
这是一个简单的交换机制。在 while 循环中,您的代码正在交换值。见附图。
您的代码只是简单地交换 text
中的字符。这里发生的是:-
您创建一个大小为 6 的字符数组 text
存储 "hello[=57=]"。
nChars
因为你已经分配代表文本中除 [=13=]
之外的字符数,所以这里是 5(类似于 strlen
)。
pStart
指向文本的第一个字母(即'h'),而pEnd
指向'o'(不是[=13= ]
).
第一个 tmp
被赋值为 'h'。然后 pStart's
字符被替换为 pEnd
的字符,即 'o'。然后 pEnd's
字符被分配给存储在 tmp
中的字符。因此 pStart
和 pEnd
中的字符被交换(但指针仍然指向相同的位置,这里要小心!)。
pStart
递增 & pEnd
递减(位置明智而不是字符明智,在这里再次小心!!)。所以现在 pStart
指向 'e' & pEnd
指向 'l'.
程序重复!!!
无法理解 while
中发生的事情 如果可能的话,请形象化。
int main()
{
char text[] = "hello";
int nChars = sizeof(text)-1;
char *pStart = text;
char *pEnd = text + nChars - 1;
//can't understand this part
while (pStart < pEnd)
{
char tmp = *pStart;
*pStart = *pEnd;
*pEnd = tmp;
pStart++;
pEnd--;
}
cout << text << endl;
return 0;
}
这是一个简单的交换机制。在 while 循环中,您的代码正在交换值。见附图。
您的代码只是简单地交换 text
中的字符。这里发生的是:-
您创建一个大小为 6 的字符数组
text
存储 "hello[=57=]"。nChars
因为你已经分配代表文本中除[=13=]
之外的字符数,所以这里是 5(类似于strlen
)。pStart
指向文本的第一个字母(即'h'),而pEnd
指向'o'(不是[=13= ]
).第一个
tmp
被赋值为 'h'。然后pStart's
字符被替换为pEnd
的字符,即 'o'。然后pEnd's
字符被分配给存储在tmp
中的字符。因此pStart
和pEnd
中的字符被交换(但指针仍然指向相同的位置,这里要小心!)。pStart
递增 &pEnd
递减(位置明智而不是字符明智,在这里再次小心!!)。所以现在pStart
指向 'e' &pEnd
指向 'l'.程序重复!!!