Character pointer problem.
This is a problem i am having when i am trying to obtain the address of a character type variable and print the address using cout. the printing works fine when i am using generic pointers by typecasting or if i use printf().
here the second cout statement fails but the fifth is OK.
Strange....
Code:
#include<iostream.h>
int main()
{
void *gp1,*gp2,*gp3;
int *ip,i;
char *cp,c;
float *fp,f;
i=10;
c='a';
f=11.11;
ip=&i;
cp=&c;
fp=&f;
gp1=ip;
gp2=cp;
gp3=fp;
cout<<endl<<"# IP:-- Integer is "<<*ip<<" at address "<<ip<<endl;
cout<<"# CP:-- Character is "<<*cp<<" at address "<<cp<<endl;
cout<<"# FP:-- Float is "<<*fp<<" at address "<<fp<<endl;
cout<<"# GP1:-- Integer is "<<*(int*)gp1<<" at address "<<gp1<<endl;
cout<<"# GP2:-- Character is "<<*(char*)gp2<<" at address "<<gp2<<endl;
cout<<"# GP3:-- Float is "<<*(float*)gp3<<" at address "<<gp3<<endl;
*ip=c;
*cp=f;
*fp=i;
cout<<endl<<"Now pointing to char by int pointer and vice versa..."<<endl;
cout<<endl;
cout<<"# IP:-- Integer is "<<*(char*)ip<<" at address "<<ip<<endl;
cout<<"# CP:-- Character is "<<*(float*)cp<<" at address "<<cp<<endl;
cout<<"# FP:-- Float is "<<*(int*)fp<<" at address "<<fp<<endl;
return 0;
}
I am using Turbo C++ 3.0 and Borland C++ 5.0 compilers...
reply on character pointer problem
int main(int argc, char* argv[])
{
void *gp1,*gp2,*gp3;
int *ip,i;
char *cp,c;
float *fp,f;
i=10;
c='a';
f=11.11;
ip=&i;
cp=&c;
fp=&f;
gp1=ip;
gp2=cp;
gp3=fp;
cout<<endl<<"# IP:-- Integer is "<<*ip<<" at address "<<ip<<endl;
cout<<"# CP:-- Character is "<<*cp<<" at address "<<cp<<endl;
//operator<< of object cout automatically interprets the pointer cp (of type char*) as a character array,
//because it accepts strings by default.
//this is why you can type the following simple statement:
//cout<<"Example";
//The string "Example" is an array of characters too.
//You also see al lot of strange looking characters after the 'a' value.
//the operator<< of cout looks for an end of string '\0' character.
//And this is not immediatly found after the character 'a'.
cout<<"# FP:-- Float is "<<*fp<<" at address "<<fp<<endl;
cout<<"# GP1:-- Integer is "<<*(int*)gp1<<" at address "<<gp1<<endl;
cout<<"# GP2:-- Character is "<<*(char*)gp2<<" at address "<<gp2<<endl;
//the above explanation explains why this statements works as desired.
//since the operator<< of cout does not recognize the type of gp2 as a char*,
//it prints the value of the pointer.
cout<<"# GP3:-- Float is "<<*(float*)gp3<<" at address "<<gp3<<endl;
*ip=c;
*cp=f;
*fp=i;
cout<<endl<<"Now pointing to char by int pointer and vice versa..."<<endl;
cout<<endl;
cout<<"# IP:-- Integer is "<<*(char*)ip<<" at address "<<ip<<endl;
cout<<"# CP:-- Character is "<<*(float*)cp<<" at address "<<cp<<endl;
//here you have the same interpretion as in the first explanation.
cout<<"# FP:-- Float is "<<*(int*)fp<<" at address "<<fp<<endl;
return 0;
}