Thread: Cycling through memory to print string with and without function problem

  1. #1
    Registered User
    Join Date
    Feb 2014
    Posts
    3

    Question Cycling through memory to print string with and without function problem

    Hello there !

    Noobie here, just joined the community ^_^

    Anyways, I have a problem where I'm trying to cycle through memory via pointers to print a string. Here is my code:

    Code:
    #include <stdio.h>
    
    int main(void){
    
        char word[]="hello there";
    
        int *pword = word;
    
        for(;*pword!='\0';pword++){
               printf("%c",*pword);
        
         }
    
        return 0;
    }

    When compiled, the returning string is "hoe".

    Funny thing is, whilst experimenting and trying to find alternate ways to get this done right, using a function to print seems to get the trick done. Here's my code using a function.


    Code:
    #include <stdio.h>
    
    int main(void){
    
        char word[]="hello there";
    
        print(word);
    
        return 0;
    }
    
    void print(char *word){
    
        for(;*word!='\0';word++){
               printf("%c",*word);
    }
    
    }
    This seems to effectively portray what I want

    How do I print a string using the same method for(;*pointer!='\0';pointer++) without a function?

    Kind regards

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Look closely at the following snippet. Do you notice any differences between the type of the variables?

    Code:
        char word[]="hello there";
     
        int *pword = word;
    Jim

  3. #3
    Registered User
    Join Date
    Feb 2014
    Posts
    3
    Quote Originally Posted by jimblumberg View Post
    Look closely at the following snippet. Do you notice any differences between the type of the variables?

    Code:
        char word[]="hello there";
     
        int *pword = word;
    Jim
    OH SHOOT! I am supposed to put char! THANK YOU

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 15
    Last Post: 06-13-2012, 12:34 PM
  2. stack problem: print after pop function
    By ivan12yu2000 in forum C++ Programming
    Replies: 1
    Last Post: 04-07-2009, 02:18 AM
  3. Problem with memory clean up in calling function
    By karthur3 in forum C Programming
    Replies: 0
    Last Post: 03-22-2009, 01:50 PM
  4. memory problem with string manipulation
    By Ichmael™ in forum C++ Programming
    Replies: 9
    Last Post: 07-10-2005, 03:09 AM
  5. Pointer/Dynamic Memory/function problem
    By Artist_of_dream in forum C++ Programming
    Replies: 17
    Last Post: 12-26-2004, 05:57 PM