2. Given the following declarations, explain why some of the following assignments are incorrect
int x = 10;
char y = 'A';
int *ptr1;
char *ptr2 = &y;
a. x = y;
b. ptr1 = ptr2;
c. ptr1 = &x;
d. x = &ptr1;
e. ptr2 = &x;
Thanks.
Answer::::
int x = 10;
char y = 'A';
int *ptr1;
char *ptr2 = &y;
These are given declarations...
For option a.) x = y;
If we assign x=y that is if we assign char to the integer variable if will print ASCII value of that character.
In the above example it will print ->> 65 which is ASCII value of 'A'.
For option b) ptr1 = ptr2;
Here ptr1 is integer pointer(int *ptr1) and ptr2 is character pointer (char *ptr2) so we cannot assign a character pointer to the integer pointer because it is assignment of incompatible types and if we print ptr1 then it will print garbage value.
for option c) ptr1 = &x;
Here we can assign a integer variable x (int x) to the integer pointer ptr1(int *ptr1) .The memory address of variable x is stored in pointer ptr1 and if we print ptr1 is shows the output as 10.
for option d) x = &ptr1;
Here we are assigning memory address of pointer ptr1 to the integer variable. Because of this assignment makes a integer from pointer (i.e memory location or address) without cast because we are storing it in a integer variable x.
If we print x then it will print garbage value.
For option e) ptr2 = &x;
Here we are storing memory address of integer variable x into pointer ptr2 . This assignment is of incompatible types.But if we print only ptr2 then it will print garbage value because incompatibility of their types.And if we print *ptr2 then it will print value at address of that variable in this it will print 10 which value of x.
Get Answers For Free
Most questions answered within 1 hours.