Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Rewriting a function using pointers

  1. May 26, 2010 #1
    I have an original code that searches through "s" for a specific character then stores this into a pointer (otherwise, null). This is the original code:
    Code (Text):
    const char* findMe(const char s[], char c)
        {
            for (int k = 0; s[k] != 0; k++)
                if (s[k] == c)
                    return &s[k];

            return NULL;
        }
    I need to rewrite it so it does the same thing but does NOT use any square brackets nor any integer variable. Here is what I have, but I am unsure of whether or not it is entirely correct;
    Code (Text):
    const char* findMe(const char* s, char c)
         {
            while (*s != '\0')
            {
                if (*s == c)
                    return &s;
            }
            return NULL;
          }
     
     
  2. jcsd
  3. May 26, 2010 #2

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    You don't need "while (*s != '\0')" just use " while (*s)"
    You don't increment s you you are only checking the first character - it will get stuck in a loop.
    Do you mean to return &s? remember S is already a pointer
     
  4. May 26, 2010 #3

    Mark44

    Staff: Mentor

    Why not copy the control structure of the first example? IOW, use a for loop instead of switching to a while loop.

    If s is declared as an array of char like this (the 30 is not relevant) -
    char s[30];

    - you can access the character at index n by array notation (s[n]) or by pointer notation ( *(s + n) ).
     
  5. May 26, 2010 #4
    i am trying to read in the whole thing, not just the first character... why is it that you only need *s and not *s != '\0'?? i thought you needed that to ensure that it gets to the zero byte/the end of the string
     
  6. May 26, 2010 #5

    Mark44

    Staff: Mentor

    The two expressions are equivalent.
    while (*s) - means "while *s is any character other than '0'
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook