C程序,为什么将char指针解引用为指针却未获得期望值 [英] C program, Why dereferece a char pointer to a pointer doesnt get expected value
问题描述
在此程序中,我具有char变量a
,b
是指向a
的指针,而c
是指向b
的指针. *a=b
时,*c
不等于b
.我不明白为什么,有人可以解释吗?
In this program I have char variable a
, b
is a pointer to a
and c
is a pointer to b
. While *a=b
, *c
not equal to b
. I don't understand why ,Can anyone explain?
我不了解的另一件事是,如果我将变量从char
更改为int
,则取消引用c
结果b
值. *c
等于b
,但是如果变量是char
类型,则不是.
Another thing I don't understand I that if I change variable from char
to int
, dereference c
result b
value. *c
equal to b
.But if variable is char
type, it does not.
#include<stdio.h>
#include<string.h>
int main()
{
char a = "a" ;
char *b;
b = &a;
printf("%d\n", b);
printf("%d\n\n", &a);
printf("Deference b* hold value: %d\n", *b);
printf("a hold value: %d\n\n", a);
char *c;
c = &b;
printf("%d\n", c);
printf("%d\n\n", &b);
printf("Deference *c hold value: %d\n", *c);
printf("b hold value: %d\n\n", b);// why *c not equal b
return 0;
}
推荐答案
首先,
char a = "a" ;
是非法的,您实际上是在试图将指针存储到char
中.您需要的是
is illegal, you're essentially trying to store a pointer into a char
. What you need is
char a = 'a' ;
然后说
printf("%d\n", b);
printf("%d\n\n", &a); //and all later pointer related prints....
在将错误类型的参数传递给%d
时,会导致未定义的行为.要打印指针,您需要
causes undefined behavior as you're passing wrong type of arguments to %d
. To print pointers, you need to
- 使用
%p
格式说明符. - 将参数传递给
void*
- use
%p
format specifier. - cast the argument to
void*
之后,
char *c;
c = &b;
也是错误的,请参见数据类型. &b
是指向char
的指针.这与char *
不同.您需要c
属于char **
类型.
is also wrong, see the data types. &b
is a pointer to pointer-to-char
. That is not the same as char *
, as you have assummed. You need c
to be of type char **
.
这篇关于C程序,为什么将char指针解引用为指针却未获得期望值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!