Help using pointers to shift characters

This is a discussion on Help using pointers to shift characters within the C Programming forums, part of the General Programming Boards category; I'm pretty new to c programming and I'm having some trouble with an assignment. I need to shift the characters ...

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    13

    Question Help using pointers to shift characters

    I'm pretty new to c programming and I'm having some trouble with an assignment. I need to shift the characters "a,b,c,d,e" 5 times using pointers and a function, so for example the next time it would display "b,c,d,e,a". I know my code is'nt the best but it seems to display random characters, altough they do seem to be shifting the correct way. Heres the code:

    Code:
    #include <stdio.h>
    void shift(char *p1, char *p2, char *p3, char *p4, char *p5);
    
    void main()
    {
    char a,b,c,d,e;
    shift(&a,&b,&c,&d,&e);
    printf("%c%c%c%c%c\n", a,b,c,d,e);
    shift(&a,&b,&c,&d,&e);
    printf("%c%c%c%c%c\n", a,b,c,d,e);
    shift(&a,&b,&c,&d,&e);
    printf("%c%c%c%c%c\n", a,b,c,d,e);
    shift(&a,&b,&c,&d,&e);
    printf("%c%c%c%c%c\n", a,b,c,d,e);
    shift(&a,&b,&c,&d,&e);
    printf("%c%c%c%c%c\n", a,b,c,d,e);
    }
    void shift(char *p1, char *p2, char *p3, char *p4, char *p5)
    {
    	char temp;
    	temp = *p1;
    	*p1 = *p2;
    	*p2 = *p3;
    	*p3 = *p4;
    	*p4 = *p5;
    	*p5 = temp;
    }
    Any help would be really appreciated.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    The reason it's displaying garbage is that your a,b,c,d,e variables are character variables, not the letters "a", "b", etc. They are uninitialized and thus are very likely to contain garbage values.

    To initialize them you need....
    Code:
    char a = 'a';
    char b = 'b';
    etc.
    I don't know if you've covered arrays yet, but this would be a good task for a small array of characters.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    13
    That got it working perfectly, thanks a million. I think we're going over arrays next, can't wait Thanks again for the quick response.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Comparing pointers
    By Deadfool in forum C Programming
    Replies: 3
    Last Post: 10-02-2008, 08:36 PM
  2. still problems with ceasar shift
    By trevordunstan in forum C Programming
    Replies: 2
    Last Post: 09-14-2008, 02:49 AM
  3. Ceasar Shift program
    By trevordunstan in forum C Programming
    Replies: 11
    Last Post: 09-11-2008, 10:40 PM
  4. HELP!!!!emergency ~expert please help
    By unknowppl in forum C Programming
    Replies: 1
    Last Post: 08-19-2008, 08:35 AM
  5. Question about pointers
    By maxhavoc in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2004, 01:46 AM

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