[英]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;
}
I am new to C++ and stack overflow.我是 C++ 和堆栈溢出的新手。
I am trying to reverse a string using pointers... I don't quite understand what I did wrong.我正在尝试使用指针反转字符串......我不太明白我做错了什么。 Please help me out.请帮帮我。
Additional question: What is the difference between a string and an array of characters?附加问题:字符串和字符数组有什么区别?
sizeof(x)
with x
being a parameter of type char[]
of a function does not give you the number of characters in the string but the size of a char*
, probably 8
on a 64 bit system. sizeof(x)
其中x
是函数的char[]
类型的参数,它不会为您提供字符串中的字符数,而是提供char*
的大小,在 64 位系统上可能为8
。 You need to pass a C-String and use strlen(x)
instead.您需要传递一个 C 字符串并使用strlen(x)
代替。 Write char text[] = {'h','e','l','l','o','\\0'}
or char text[] = "hello"
in main
.在main
写入char text[] = {'h','e','l','l','o','\\0'}
或char text[] = "hello"
。
Note that sizeof()
needs to be evaluatable at compile time;请注意, sizeof()
需要在编译时进行评估; this is not possible on arrays with undetermined size like char[]
-typed function arguments.这在大小不确定的数组上是不可能的,比如char[]
类型的函数参数。 When using sizeof
on a variables like your char text[] = {'h','e','l','l','o'}
, however, sizeof(text)
will result in the actual size of the array.但是,当对像char text[] = {'h','e','l','l','o'}
这样的变量使用sizeof
时, sizeof(text)
将导致数组的实际大小.
char x[]
is the same as char* x
and the sizeof(x)
is therefore the size of a pointer. char x[]
与char* x
相同,因此sizeof(x)
是指针的大小。 So, because you cannot calculate the size of an array outside of the block it is declared in, I would eliminate that part from your function.因此,因为您无法在声明它的块之外计算数组的大小,所以我将从您的函数中删除该部分。
It would be much easier to provide the function with pointers to the first and last characters to be replaced:为函数提供指向要替换的第一个和最后一个字符的指针会容易得多:
void reverse(char* pStart, char* pEnd)
{
while (pStart < pEnd)
{
char temp = *pStart;
*pStart = *pEnd;
*pEnd = temp;
pStart++;
pEnd--;
}
}
So now it is quite easy to call this function - take the address (using ampersand &
) of the the relevant characters in the array: &text[0]
and &text[4]
.所以现在很容易调用这个函数 - 获取数组中相关字符的地址(使用和号&
): &text[0]
和&text[4]
。
To display an array of characters, there is a rule, that such "strings" HAVE to have after the last character a NULL character.要显示字符数组,有一条规则,即此类“字符串”必须在最后一个字符之后有一个 NULL 字符。 A NULL character can be written as 0
or '\\0'
. NULL 字符可以写为0
或'\\0'
。 That is why it has to be added to the array here.这就是为什么必须将其添加到此处的数组中的原因。
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.