C program, Why dereferece a char pointer to a pointer doesnt get expected value

柔情痞子 提交于 2019-12-12 04:08:15

问题


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?

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;

}

回答1:


First of all,

 char a =  "a" ;

is illegal, you're essentially trying to store a pointer into a char. What you need is

char a =  'a' ;

Then, saying

printf("%d\n", b);
printf("%d\n\n", &a);  //and all later pointer related prints....

causes undefined behavior as you're passing wrong type of arguments to %d. To print pointers, you need to

  • use %p format specifier.
  • cast the argument to void*

After that,

char *c;
c = &b;

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 **.




回答2:


Look at the compiler warnings, maybe you want this:

int main()
{
    char *a = "a";
    char *b;    

    b = a;
    printf("%p\n", b);
    printf("%p\n\n", &a);
    printf("Deference b* hold value: %d\n", *b);
    printf("a hold value: %p\n\n", a);
    char *c;
    c = b;
    printf("%p\n", c);
    printf("%p\n\n", &b);
    printf("Deference *c hold value: %d\n", *c);
    printf("b hold value: %p\n\n", b);// why *c not equal b
    return 0;    
}


来源:https://stackoverflow.com/questions/43320263/c-program-why-dereferece-a-char-pointer-to-a-pointer-doesnt-get-expected-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!