[英]Reversing a string in C++ using pointers
void reverse(char[] x) {
char* pStart = x;
char* pEnd = pStart + sizeof(x) - 2;
while(pStart < pEnd) {
char temp = *pStart;
*pStart = *pEnd;
*pEnd = temp;
pStart++;
pEnd--;
}
}
int main() {
char text[] = ['h','e','l','l','o'];
reverse(text);
cout << text << endl;
return 0;
}
我是 C++ 和堆栈溢出的新手。
我正在尝试使用指针反转字符串......我不太明白我做错了什么。 请帮帮我。
附加问题:字符串和字符数组有什么区别?
sizeof(x)
其中x
是函数的char[]
类型的参数,它不会为您提供字符串中的字符数,而是提供char*
的大小,在 64 位系统上可能为8
。 您需要传递一个 C 字符串并使用strlen(x)
代替。 在main
写入char text[] = {'h','e','l','l','o','\\0'}
或char text[] = "hello"
。
请注意, sizeof()
需要在编译时进行评估; 这在大小不确定的数组上是不可能的,比如char[]
类型的函数参数。 但是,当对像char text[] = {'h','e','l','l','o'}
这样的变量使用sizeof
时, sizeof(text)
将导致数组的实际大小.
char x[]
与char* x
相同,因此sizeof(x)
是指针的大小。 因此,因为您无法在声明它的块之外计算数组的大小,所以我将从您的函数中删除该部分。
为函数提供指向要替换的第一个和最后一个字符的指针会容易得多:
void reverse(char* pStart, char* pEnd)
{
while (pStart < pEnd)
{
char temp = *pStart;
*pStart = *pEnd;
*pEnd = temp;
pStart++;
pEnd--;
}
}
所以现在很容易调用这个函数 - 获取数组中相关字符的地址(使用和号&
): &text[0]
和&text[4]
。
要显示字符数组,有一条规则,即此类“字符串”必须在最后一个字符之后有一个 NULL 字符。 NULL 字符可以写为0
或'\\0'
。 这就是为什么必须将其添加到此处的数组中的原因。
int main()
{
// char text[] = "hello"; // Same like below, also adds 0 at end BUT !!!in read-only memory!!
char text[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
reverse(&text[0], &text[4]);
std::cout << text << std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.