【问题标题】:unable to print string after reversing in C在 C 中反转后无法打印字符串
【发布时间】:2021-09-26 07:34:26
【问题描述】:

我写了下面的程序来反转字符串,但是反转后没有打印出来。 可能是什么问题?

#include<stdio.h>
#include<string.h>

main()
{
    char p[] = "krishna";
    
    strrv(p);
    printf("%s", p);    // -----> nothing prints here
}

void strrv(char p[])
{
    int l = strlen(p);
    int i=0;
    char tmp;
    
    
    while(i<l)
    {
        tmp = p[i];
        p[i] = p[l];
        p[l] = tmp;
        
        i++;
        l--;
    }
}

【问题讨论】:

  • 首先,关于在调用函数之前声明函数,您的教科书是怎么说的?其次,你的教科书对字符串有什么看法,更准确地说是关于它们是如何以空终止的?你的函数是否也反转了那个空终止符?
  • 您真的应该以此为契机学习两件事:使用额外警告进行构建,以及将编译器生成的所有警告视为必须修复的实际错误;以及如何调试您的代码,例如,通过使用调试器逐条执行代码语句,同时监控变量及其值。
  • 有大量关于如何反转字符串的代码示例。你看过其中一个吗?

标签: c string


【解决方案1】:

在第一次循环迭代中,p[l] 将引用 p 的终止 \0,然后将其分配给 p[0],这反过来又使 p 成为空字符串。修复方法是将l 初始化为strlen(p) - 1 而不是strlen(p)

#include <stdio.h>
#include <string.h>

void strrv(char p[]) {
    for(int i = 0, l = strlen(p) - 1; i < l; i++, l--) {
        char tmp = p[i];
        p[i] = p[l];
        p[l] = tmp;
    }
}

int main() {
    char p[] = "krishna";
    strrv(p);
    printf("%s", p);
    return 0;
}

【讨论】:

    【解决方案2】:
    int l = strlen(p);
    

    这必须用int strlen(p)-1初始化,否则你把最后的NUL '\0' (null character)移到第一个位置。

    【讨论】:

    • 你的意思是一个空的字符,它在ASCII中被命名为NUL,而不是NULL,它是一个指针
    • @CiaPan 正确,字符串和字符串文字的结尾被命名为 NUL。谢谢。
    • @CiaPan 最近创造了 NUL,因为在 C 的旧书中它被写成“final null”。
    • “最近”到底是什么时候开始的?这张来自 Wikipedia 的图表使用了 NUL,显然是在 1970 年初的 USASCII code chart.png 和这部分 ASCII, Control code chart 说 NULL 在 1965 年已被 NUL 取代。
    • @CiaPan Kernighan Ritchie 第 2 版:第 31 页这样说:GETLINE puts the character '\0' (the null character, whose value is zero) at the end of the array it is creating, to mark the end of the string of characters. This conversion is also used by the C language: when a string constant like "hello" appears in a C program..."。如果 Kernighan 错了,我也宁愿错,其余的我不关心。我在其他名著中也看到过同样的教派。
    猜你喜欢
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2019-02-14
    • 1970-01-01
    • 2014-01-12
    相关资源
    最近更新 更多