在 C 中反转字符串 - 指针? [英] Reversing a string in place in C - pointers?

查看:51
本文介绍了在 C 中反转字符串 - 指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能帮我理解 line2:char * end = str 和 line4:if (str) 做什么?

Can someone help me understand what line2:char * end = str and line4:if (str) do?

void reverse(char *str) { 
   char * end = str; 
   char tmp;
   if (str) {
      while (*end) { 
         ++end;
      }
      --end;
      while (str < end) {
         tmp = *str; 
         *str++ = *end; 
         *end-- = tmp;
      } 
   }
} 

推荐答案

if (str) 测试可保护您免于取消引用空指针和崩溃.

The if (str) test protects you from dereferencing a null pointer and crashing.

定义char *end = str;定义了变量end,一个字符指针,并用str中存储的值对其进行初始化(这是str指向的字符串的第一个字符的地址).

The definition char *end = str; defines the variable end, a character pointer, and initializes it with the value stored in str (which is the address of the first character of the string that str points to).

剩下的代码决定了字符串的长度,然后安排从两端交换字符对,朝着字符串的中间移动.从技术上讲,如果原始代码传递一个空字符串(指向字符串末尾空字节的指针),则它是不安全的.那是因为它会将 end 递减到 str 指向的字节之前的一个字节.但是,不能保证字符串开头前一字节的地址是有效的.该字符串可能指向内存页面的第一个字节,而之前的页面从未被映射,从而导致崩溃或其他问题.

The rest of the code determines the length of the string, and then arranges to swap pairs of characters from the two ends, working towards the middle of the string. Technically, the original code is not safe if it is passed an empty string (a pointer that points to the null byte at the end of a string). That's because it will decrement end to one byte before the byte that str points at. However, there is no guarantee that the address one byte before the start of a string is valid. The string might point to the first byte of a page of memory, and the prior page has never been mapped, leading to crashes or other problems.

最好使用strlen()来确定字符串的长度.

It would be better to use strlen() to determine the length of the string.

void reverse(char *str)
{ 
    if (str != 0 && *str != '\0') // Non-null pointer; non-empty string
    {
        char *end = str + strlen(str) - 1; 

        while (str < end)
        {
            char tmp = *str; 
            *str++ = *end; 
            *end-- = tmp;
        } 
    }
}

这篇关于在 C 中反转字符串 - 指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆