c - 我如何使用其他变量打印 ascii 代码?

标签 c string pointers type-conversion

我正在学习C语言。

这是我的代码

int main(void)
{
    char * character = "abcd";

    printf("%d \n", *character);

    int num = character;
    int * pnum = #

    printf("%s \n", * pnum);

    return 0;
}

我得到的结果是:97 和 abcd。

我了解到 97 是 'a' 的 ascii 码。

我想要结果 97 使用 pnum 变量,

所以我尝试了 printf("%d", pnum) , printf("%d", *pnum) 或其他东西。

但是我还不能从 pnumnum 得到 97。

如何使用 pnumnum 得到 97?

最佳答案

通常程序有未定义的行为 . 根据C标准(6.3.2.3指针)

6 Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

例如sizeof( char * ) sizeof( int ) 可以等于 8可以等于 4。那是一个 int 类型的对象不能存储指针的值。

而不是类型 int在这份声明中

int num = character;

你应该使用类型 intptr_t在 header 中声明 <stdint.h>

例如

#include <stdint.h>

//...

intptr_t num = ( intptr_t )character;

所以现在变量 num包含字符串文字第一个字符的地址 "abcd" .

在声明之后

intptr_t *pnum = &num;

指针pnum有变量的地址 num .

现在要输出字符串文字的第一个字符,您首先要取消引用指针 pnum获取存储在变量 num 中的值.该值表示字符串文字的第一个字符的地址。您需要将其转换为类型 char *并再次取消引用它。

下面是一个演示程序,展示了它是如何实现的。如果您不取消引用指针,则将输出整个字符串文字。

#include <stdio.h>
#include <stdint.h>


int main(void) 
{
    char *character = "abcd";

    printf( "%d\n", *character);

    intptr_t num = ( intptr_t )character;
    intptr_t *pnum = &num;

    printf( "%s\n", ( char * )*pnum );
    printf( "%d\n", *( char * )*pnum );

    return 0;
}

程序输出为

97
abcd
97

关于c - 我如何使用其他变量打印 ascii 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45116421/

相关文章:

c - fork后如何通过键盘在子进程中引入字符串

c - 在C中制作类似strcmp()的函数

ruby - 查看 ruby​​ 字符串中是否有空格

c# - 为什么字符串指针位置不同?

c - 把一个词变成***符号

c - Visualstudio.com 认为最新的 libgit2 已过时

c - 读取文件并存储到变量中

c - 如何正确测试c中的空字符串

c++ - 打印此地址的值

c - 在 C 中使用指针和数组