I just found a question whose statement is as follows:

Write a function contains(const char*, char) which returns the pointer to the first (left-most) occurrence of the 2nd parameter char in the 1st parameter cstring, or NULL if the cstring doesn't contain the char.
Another condition is that inside the function we are allowed to use only the pointer notation(*) to manipulate the array and not to use the normal array index [] notation.

I have written the following code:

#include <iostream>
using namespace std;

char *contains(const char*, char);

int main()
{
	char myString[101];
	cout << "Enter a string of 100 or less characters:\n";
	cin.getline(myString, 100);
	char keyChar;
	cout << "Which character do you want to find in this string?\n";
	cin >> keyChar;
	char *storePtr = contains(myString, keyChar);
	if (storePtr == 0)
		cout << "Sorry! The character you specified was not found in the string you entered!\n";
	else
	{
		cout << keyChar << " is stored at memory location " << storePtr;
		cout << "." << endl;
		cout << "By dereferencing it, we get " << *storePtr << " which confirms that our function is working correctly.\n";
	}

	system("pause");
	return 0;
}

char *contains(const char *myStr, char c)
{
	char *keyPtr=0;
	for (int i=0; *(myStr+i)!='\0'; i++)
	{
		if (*(myStr+i)==c)
		{
			keyPtr = (char*)(myStr+i);
			break;
		}
	}
	return keyPtr;
}

It is working fine as far as the requirements of the question are concerned. But one line in this code is behaving in a somewhat strange manner to me. That line is: cout << "By dereferencing it, we get " << *storePtr What it does is it starts at the location pointed to by "storePtr" and prints out all next characters uptill the null character.
What I was expecting is that it should print the hexadecimal memory address contained in the pointer "storePtr". Then it came into my mind that it is completely in accordance with what "cout" does when we pass the name of a character array to it.

But I am curious to know if there is a way to output the address contained in such a pointer, too???? Actually I just searched the Internet about it and I found a way to do this in C using printf() so I think that there would be an analogous in C++ too.

Edited 5 Years Ago by Muhammad Anas: n/a

Pointers to char are assumed to be C-style strings by cout. You can force them to be interpreted as pointers by casting to void*:

cout<< (void*)p <<'\n';
Comments
Thanks for the help!!!!!

Oh ... OKKKKK
It really worked!!
Thank you very much!!!!!!!!!!!!

Edited 5 Years Ago by Muhammad Anas: n/a

This question has already been answered. Start a new discussion instead.