Pointer arithmetics

This is a discussion on Pointer arithmetics within the C Programming forums, part of the General Programming Boards category; This is how to set the pointer to a certain point in a string: Code: int main() { char * ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    790

    Pointer arithmetics

    This is how to set the pointer to a certain point in a string:

    Code:
    int main()
    {
        char * response = "hello world";
        for(int i=0;i<6;i++) *response++;
        printf("%s\n", response);
    
        return 0;
    }
    Now how to set it back to position 0 ?
    Is there an easier way than using a for() loop backwards?
    Compiler MSVC++ 2013 with Code::Blocks.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    In this case you can do
    Code:
    response -=6;
    in much the same way as you don't need the for loop to go forward either. If you find yourself doing this often, you should probably set up another pointer to always point at the front of the string, so that you can reset your walking pointer by reassigning it the value of your stationary pointer.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    790
    Perfect!

    Thanks a lot Tabstop!
    Compiler MSVC++ 2013 with Code::Blocks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Quick Pointer Question
    By gwarf420 in forum C Programming
    Replies: 15
    Last Post: 06-01-2008, 03:47 PM
  3. Parameter passing with pointer to pointer
    By notsure in forum C++ Programming
    Replies: 15
    Last Post: 08-12-2006, 07:12 AM
  4. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21