J Nguyen
J Nguyen

Reputation: 147

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

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;

}

Upvotes: 0

Views: 102

Answers (2)

Jabberwocky
Jabberwocky

Reputation: 50822

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;    
}

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

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

Upvotes: 4

Related Questions