Thread: Some question about strings

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    3

    Some question about strings

    I've been given a code:

    Code:
    char *advance(char *ptr)
    {
       return ptr++;
    }
    
    int main() {
        char *ptr="12";
        advance(ptr);
        ptr=advance(ptr);
        printf("%c",*ptr);
        return 0;
    }
    And I'm asked what is the output. I found out that the output is 1 by compiling the code, but I don't really know why. Seems like advance() doesn't change the string, although it gets a pointer to it.

    I'll appreciate any help.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    use
    Code:
    return ++ptr;
    instead.

    ptr++ retuns the original pointer and then increments.

    Kurt

  3. #3
    Registered User
    Join Date
    Aug 2008
    Posts
    3

    Thank you

    Maybe you have a link to some material that explains the difference between prefix and postfix operators a little more clearly?

    And about this question, again, what about the line advance(ptr)? It doesn't change anything?

    Thanks again.

  4. #4
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    That's what your program actually does

    1) a copy of ptr in main is passed to advance.
    2) the value of that pointer is copied to a temporary.
    3) the argument ptr of advance is incremented
    4) the temporary ( the same value that was passed ) is returned
    effectively the call to advance does not change anything in main.
    Kurt

  5. #5
    Registered User
    Join Date
    Aug 2008
    Posts
    3
    And if I would want to change advance() so that it actually will advance the pointer, what I need to do? Send advance(&ptr) and change to advance(char **ptr)?

  6. #6
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Just changing the parameter to a reference wouldn't change anything.
    You would also have to change advance to not return the pointer, or remove the assignment in main.
    The easiest solution is in my 1st reply.
    But why don't you just modify your code and see what happens ?
    Kurt

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about strings in c
    By gp364481 in forum C Programming
    Replies: 9
    Last Post: 11-13-2008, 06:32 PM
  2. Question About Strings
    By spanker in forum C++ Programming
    Replies: 1
    Last Post: 07-13-2008, 05:09 AM
  3. strings question
    By cstudent in forum C Programming
    Replies: 4
    Last Post: 04-18-2008, 07:28 AM
  4. Functions and Strings Question
    By StrikeMech in forum C Programming
    Replies: 4
    Last Post: 07-18-2007, 06:07 AM
  5. Strings question
    By kimimaro in forum C Programming
    Replies: 10
    Last Post: 03-15-2005, 12:14 AM