Pointer refering to variable of other datatypes

As said in video we should not assign pointer of one datatype to address of a variable of other data types, in case pointer of type char is assigned address of int variable than it should read only one byte of data that is in case of 14 it will just output either 1 or 4 only but on doing the same I am getting compilation error , which I should get, from my prior knowledge
code:
#include

using namespace std;

int main() {
int c = 1;
int b = 12;
int d = 123;
int a = 1234;

char * p = &a;
char *q= &b;
char *r = &c;
char *s = &d;

cout<<*p<<endl;
cout<<*q<<endl;
cout<<*r<<endl;
cout<<*s<<endl;

// cout<<"Sum of x+y = " << z;
return 0;

}
output: compilation error:
I am unable to understand this concept please make me understand this.

Hello @Divya_321,

  1. Yes, you have stated the correct reason for not assigning the address of a variable of one type to a pointer of another type.
    But, you have understood the concept wrongly.
    Data is stored in memory in binary format i.e. in the combination of 0 and 1.

    Int requires 4 bytes and char requires 1 byte.
    Each byte has 8 bits.
    So, the binary representation of 14 is 1110
    when 14 will be stored in memory, 1110 will be the rightmost 4 bits of the 4 bytes representation and rest all bits will be 0.
    So, if you will make use pointer of char type, then it will read the leftmost 1 byte i.e. 8 bits (00000000) and will print 0, not 1.

  2. Now, coming to the second part of your question.
    When do we get an error?
    When you write a statement that violates the rules written in the documentation or specification of the language. Correct?

    This is the case here.
    You are getting an error that states exactly the same that you have been explained in the video:

prog.cpp:10:13: error: _cannot convert 'int’ to 'char’ in initialization_**
char * p = &a;

In the video, Sir is trying to explain to you the reason of this error.
But, it is one of the rules that is specified in the documentation of the language that your code should follow, else it will produce an error.

Hope, I have cleared your doubt.
Give a like, if you are satisfied.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

your explanation is really great