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.

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';
commented: Thanks for the help!!!!! +1

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

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.