gpt4 book ai didi

反转字符串的 C 代码 - 包括字符串末尾的 NULL 字符

转载 作者:行者123 更新时间:2023-11-30 20:55:39 25 4
gpt4 key购买 nike

1.) 是否可以反转包含 NULL 字符的字符串(这意味着“abcd”表示为五个字符,包括空字符。)

2.) 在我当前的实现中,没有考虑 1.) ,我在交换过程中遇到段错误。即分配时:*str = *end;

void reverse(char *str)
{
char * end = str;
char tmp;
if (str)
{ // to handle null string
while (*end)
{ // find the end character
++end;
}
--end; // last meaningful element
while (str < end) // terminal condition: str and end meets in the middle
{ tmp = *str; // normal swap subroutine
*str = *end; // str advance one step
*end = tmp; // end back one step

str++;
end-- ;
}
}
return;
}

最佳答案

你的函数是正确的。问题似乎在于您正在尝试反转字符串文字。您不能更改字符串文字。它们是一成不变的。任何更改字符串文字的尝试都会导致程序的未定义行为。

来自 C 标准(6.4.5 字符串文字)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined

只考虑这样写会比较好

if ( *str )

而不是

 if (str)

或者,如果你想检查指针是否不为 NULL,那么

if ( str && *str )

在这种情况下,这个减量

--end;

即使原始字符串为空也有效。

尽管如此,函数本身可以按照演示程序中所示的以下方式定义

#include <stdio.h>

char * reverse( char *s )
{
char *last = s;

while ( *last ) ++last;

if ( last != s )
{
for ( char *first = s; first < --last; ++first )
{
char c = *first;
*first = *last;
*last = c;
}
}

return s;
}

int main( void )
{
char s[] = "Hello arshdeep kaur";

puts( s );
puts( reverse( s ) );
}

程序输出为

Hello arshdeep kaur
ruak peedhsra olleH

关于反转字符串的 C 代码 - 包括字符串末尾的 NULL 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31547296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com