I'm trying something like this

void receiver (char* x)
{
    cout<<x<<endl; //prints "a"
    cout<<*x<<endl; //prints "a"
    cout<<&x<<endl; //prints address of x
}

int main()
{
    char p = 'a';
    cout<<p<<endl; //prints "a"
    cout<<&p<<endl; //prints "a"
    receiver(&p);
}

In the main function for both p and &p, it is printing the value of p.
If it is int instead of char, then p would print the value and &p would print the address. Why is this strange behavior with char?

I'm surprised lines 3 and 12 display "a" actually. I'm wondering if it's dumb luck. I would expect the FIRST character printed to be 'a', but after that, since you have no null terminator, I'd say it's undefined behavior. Potentially you could just print stuff forever. char* is assumed to represent a null-terminated string of characters, not a pointer to a char. It's not "strange", it's just a special case.

Yes, even I'm surprised with line 12. That's why I posted it here in case anybody has an answer for that.

I get the point in line 3 though
char* x represents a string.
if cout x, then it'll print the whole string
if cout *x, then it'll print the first character in the string. Maybe since my string is only 1 character long, you got confused.

Can anybody tell me how to get the memory address where the character 'a' is located?

>> Maybe since my string is only 1 character long

You don't have a string. A string is an array of characters with a null terminator. You have one character and no null terminator.

>> Can anybody tell me how to get the memory address where the character 'a' is located?

You can use printf and specify the %p format, which always displays addresses.

#include <cstdio>
using namespace std;


int main()
{
    char p[2];
    p[0] = 'a';
    p[1] = 0;
    printf("%s %c %p\n", p, *p, p);
    return 0;
}

Hello subith86,
Declare a pointer variable and use it to store the address of the char variable p.

char *b,p='a';
b=&p;
cout<<&b;

thanks all... got it :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.