Akhil Raj
Akhil Raj

Reputation: 477

What does pointer variable store?

I typed in this code:

char *a;
char b = 'd';
a = b;
printf("%c", a);

Output - 'd'.

My query is that since a is pointer variable, it is supposed to store address. Why in this case is it storing character value?

Upvotes: 0

Views: 1530

Answers (4)

Hamidreza Soleimani
Hamidreza Soleimani

Reputation: 2554

Although your code output seems to be working based on the reasons that @dasblinkenlight told, that is not a correct practice to assign a char to a char*. The compiler (GCC 4.8.4) warning also is helpful to understand the issue:

warning: assignment makes pointer from integer without a cast [enabled by default]
  a = b;
    ^

When you assign an int to a int* the compiler prints such warning. It also applies to char and char* in the same way because a char is a form of int in C.

Upvotes: 0

Neeraj Shivam
Neeraj Shivam

Reputation: 11

Talking in reference with C, a pointer variable stores the address of the variable it is pointing to. In C we cannot use it like any other ordinary variable to store other type of data. Moreover, the datatype of the pointer variable is the variable pointing to or if we declare it as void we need to cast it in as per necessity(i.e. the data type of pointing variable).

Talking in reference to your query, since you have already declared it as "pointer variable" so the function of "printf" is to print the data the pointer variable is pointing to.

Upvotes: 0

embbeded
embbeded

Reputation: 1

pointer is a variable which stores the address of the another variable.but here you wrote a=b which means your are providing the character d to which will the a store.this is because the pointer is also a variable.it is also having its own address space.while we provide the address of the another variable the pointer stores that address that means pointer have the storing capacity. but in this program you cant dereference the pointer.you will get segmentation fault.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

since a is pointer variable, it is supposed to store address

A pointer variable can store numeric values, too. On most systems a pointer variable could store an int, although there is no explicit guarantee of this. However, a pointer variable is capable of storing a value of type char on all systems.

then why in this case is it storing character value?

Because you told it to do so. Storing a value in a pointer does not make that value an address.

Note: your code has undefined behavior. The reason the code produces the output that you expect is that a pointer representation on your system happens to be compatible with that of an int, which is what %c expects.

Upvotes: 8

Related Questions