Pointers Fuctions

May 9, 2010 at 11:18pm
I am currently doing a practice problem for an upcoming exam,but I'm am unsure of what to do when the instruction says to "Return the pointer to the first appearance of c appearing inside s". So if anyone could point me in the right direction I would be very grateful.


#include <iostream>
#include <string>

using namespace std;

char my_strchr(const char * s, char c)
{

if (c != *s)
{
return 0;
}

}

int main()
{
char cstr[50] = "Abadabadoo!";
cout << my_strchr(cstr, 'a') << endl;
}
May 9, 2010 at 11:25pm
closed account (Lv0f92yv)
You are given a char array, and can iterate over it by the following:

1
2
3
4
for ( int i = 0; i < strlen( s ); i++ )
{
   cout << s[i]; //is the char at offset 'i'
}


, from here, you can determine the position of 'c' at 's'. Hope this helps.

Edit: Your return value is a pointer to this position in this array. If you're not sure how to return a pointer to that, check out pointer arithmetic: http://www.cplusplus.com/doc/tutorial/pointers/
Last edited on May 9, 2010 at 11:27pm
May 9, 2010 at 11:41pm
Thanks Desh! Though, is there a way to do it without strlen()?
May 9, 2010 at 11:48pm
closed account (Lv0f92yv)
Maybe you could try this:
1
2
3
4
for ( int i = 0; s[i] != '\0'; i++ )
{
   cout << let[i];
}


note the loop condition: as long as the char at offset 'i' isn't the null terminator character, keep incrementing the offset.

Why don't you want to use strlen?
Last edited on May 9, 2010 at 11:49pm
May 9, 2010 at 11:51pm
Once again THANK YOU :D.I had forgotten to mention that the instruction forbids the use of C++ string class or C-style string functions in the standard library, including strlen() for the following function. Sorry about that that.
Last edited on May 9, 2010 at 11:55pm
May 10, 2010 at 12:21am
closed account (Lv0f92yv)
Ahh I see. Figured it was something like that. No worries.
Topic archived. No new replies allowed.