我正在学习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)
或其他东西。
但是我还不能从 pnum
和 num
得到 97。
如何使用 pnum
或 num
得到 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 = #
指针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 = #
printf( "%s\n", ( char * )*pnum );
printf( "%d\n", *( char * )*pnum );
return 0;
}
程序输出为
97
abcd
97
关于c - 我如何使用其他变量打印 ascii 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45116421/