c - 反向打印字符串而不在代码中反转

标签 c printf character constants string-literals

我尝试通过三元运算符声明它来打印字符串。它不会出现任何错误,而是相反地打印字符串。

有人可以解释一下吗?

我期望根据输入将字符串打印为

 #include<stdio.h>

    void main()
    {
        int a;
        char *num;

        printf("Enter a number: ");
        scanf("%d", &a);

        num = (a % 2) ? 'odd' : 'even';

        printf("Its %s number", &num);

        getch();
    }

最佳答案

'odd''even' 是整型字符常量。

根据C标准(6.4.4.4字符常量)

10 An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.

所以在这次通话中

printf("Its %s number", &num);

您正在尝试将变量num的地址输出为字符串的地址,即您正在尝试输出字符串,但num并不指向字符串。

您必须使用字符串文字而不是字符常量。

你的意思是下面的内容

    num = (a % 2) ? "odd" : "even";

    printf("Its %s number", num);

关于c - 反向打印字符串而不在代码中反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57475754/

相关文章:

jquery - 如何解码从 jQuery 的 keydown() 事件处理程序中按下的字符

windows - Dos/Windows 批量插入符号在 set/P 提示符下转义

检查两个字符数组是否相等 C

c++ - MathGL BoxPlot 的数据格式

java - 如何使用输入大小修饰符打印长类型值?

c - 在C中使用printf加载点效果

c++ - 如何知道用于构建 linux 的 gcc 版本?

c++ - 为什么我们需要 *.lib 文件?

c - 如何在C中使用一条printf语句多次打印变量

c - 从函数中替换 char[] 中的字符