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 ++的新手,并且堆栈溢出。
我正在尝试使用指针来反转字符串...我不太了解自己做错了什么。请帮帮我。
其他问题:字符串和字符数组有什么区别?
答案 0 :(得分:1)
sizeof(x)
,其中x
是函数的类型char[]
的参数,它不能为您提供字符串中的字符数,但可以为您提供char*
的大小8
在64位系统上。您需要传递C字符串,并使用strlen(x)
代替。在char text[] = {'h','e','l','l','o','\0'}
中写入char text[] = "hello"
或main
。
请注意,sizeof()
需要在编译时进行评估;对于大小不确定的数组(例如char[]
类型的函数参数),这是不可能的。但是,在像sizeof
这样的变量上使用char text[] = {'h','e','l','l','o'}
时,sizeof(text)
将导致数组的实际大小。
答案 1 :(得分:0)
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;
}