C程序,为什么将char指针解引用为指针却未获得期望值 [英] C program, Why dereferece a char pointer to a pointer doesnt get expected value

查看:144
本文介绍了C程序,为什么将char指针解引用为指针却未获得期望值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此程序中,我具有char变量ab是指向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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆