1
char srch(char x[],char k){
int i=0;
while(x[i]!='\0')
{
    if(k==x[i])
    {
       const char *h=&(x[i]);
       const void *l = h;
       cout<<"\n\nTHE CHARACTER "<<x[i]<<" FOUND AT ADDRESS "<<l<<"\n\n\n";
       exit(0);
    }
    i++;
}
return NULL;
}

int main(){
system("cls");
char str[20],ch;
cout<<"ENTER THE STRING:-\n";
gets(str);
cout<<"ENTER THE CHARACTER WHICH YOU WANT TO SEEK:-\n";
cin>>ch;

srch(str,ch);

if(NULL);
cout<<"\n\nCHARACTER NOT FOUND ";}

NOW, if my string is "tarun" and my character to be seeking is 'a' then it perfectly shows the address of 'a'. BUT If I replace my srch function by this:-

    char srch(char x[],char k){
int i=0;
while(x[i]!='\0')
{
    if(k==x[i])
    {
       const char *h=&(x[i]);
       const char *l = h;
       cout<<"\n\nTHE CHARACTER "<<x[i]<<" FOUND AT ADDRESS "<<l<<"\n\n\n";
       exit(0);
    }
    i++;
}
return NULL;}

then instead of the address, it shows arun. Why this happened when I used char* instead of void* ?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Tarun Bisht
  • 121
  • 13

1 Answers1

4

Character pointer (char*) has overloaded output operator (operator<<), and prints underlying C-style string instead of adress of a pointer. This overload exists in order to support code like this:

std::cout << "some string";

"some string" type is actually const char*, without the overload it would print an adress of string instead of the string itself.

Void pointer (void*), or any other pointer type (AFAIK) doesn't provide this kind of overload, so the printed value is pointer adress.

Outshined
  • 709
  • 7
  • 22