pointer increments

This is a discussion on pointer increments within the C++ Programming forums, part of the General Programming Boards category; I am trying to figure out pointer increment here...with method that finds length I run the program and i get ...

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    266

    pointer increments

    I am trying to figure out pointer increment here...with method that finds length

    I run the program and i get a scrolling mess of characters flying by till program crashes..lol

    Code:
    #include <iostream>
    using namespace std;
    
    int length( char *c ) {
    	int cnt=0;
    	if(c)                            //check to make sure pointer isnt null.
    		for(;c++;cnt++)           //keep running till reach null \0, increment the cnt variable each time.
    			cout << *c;
    	else
    		return 0;
            c-=cnt;
    	return cnt;
    }
    
    int main()
    {
        char *st = "hello world";
    	cout << endl <<length(st);
        return 0;
    }
    Last edited by rodrigorules; 11-21-2009 at 10:20 PM.

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,308
    Since c is a pointer and you're interested at the characters it points at, you'll need to use a * somewhere to dereference your pointer other than where you just print it.

    You don't have to adjust the pointer back to where it started before the function returns.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 03-24-2008, 10:16 AM
  2. Replies: 0
    Last Post: 03-20-2008, 07:59 AM
  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. How did you master pointers?
    By Afrinux in forum C Programming
    Replies: 15
    Last Post: 01-17-2006, 07:23 PM

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