gpt4 book ai didi

c - C 中指向常量的指针

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:41 25 4
gpt4 key购买 nike

我编译了下面的代码:

#include <stdio.h>

int main(void) {
// your code goes here

char *consta = "ABC";

printf("Use of just const: %c\n", consta );
printf("Use of const[1]: %c\n", consta[1]);
printf("Use of whole string: %s", consta);

return 0;
}

但是,我得到的输出是:

Use of just const: P
Use of const[1]: B
Use of whole string: ABC

第二个 printf 和第三个 printf 函数调用按预期工作,但是,我期望在第一次调用 printf 时打印“A”而不是“P”。

最佳答案

consta 是指向字符的指针。格式说明符 %c 需要类型为 char(字符) 的参数,而不是 char*(指向特点)。您的代码表现出未定义的行为。尝试取消引用 consta :

printf("Use of just const: %c\n", *consta);

其中 *consta 顺便等于 consta[0]

† 实际上,参数是 int 类型,并被 printf() 转换为 unsigned char。这与适用于具有可变参数的函数的参数提升规则有关;类型为 charprintf() 参数在传递给 printf() 之前被提升为 int,这这就是 printf() 必须将其提升回来的原因。对于大多数程序而言,差异无关紧要。

关于c - C 中指向常量的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25978841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com