Thread: Reverse a message using pointers.

  1. #1
    Registered User
    Join Date
    Jul 2010

    Reverse a message using pointers.

    I am trying to reverse a message using pointers but I get only the last character of the message.
    Here's the code :
    #include <stdio.h>
    #include <stdbool.h>
    #include <stdlib.h>
    int main (int argc, const char * argv[]) {
        char myArray[100];
    	char ch;
    	int n = 0;
    	//int counter;
    	int *p;
    	//get user input
    	printf("Enter a mesage: ");
    	ch = getchar();
    	while (ch != '\n') {
    		myArray[n] = ch;
    		ch = getchar();
    	}//end while
    	printf("Reversal is: ");
    	for (p = &myArray[n - 1]; p >= &myArray[0]; p--) {
    		printf("%c", *p);
    The problem should be in the result section.
    Am I doing something wrong there?
    Last edited by skiabox; 11-18-2010 at 09:03 AM.

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Oregon, USA
    Change your pointer to type char * instead of int * since it's pointing to an array of chars, not ints.

    Turn on your compiler warnings. The compiler should have alerted you to a at least a couple of problems.
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Jul 2010
    You were right.I thought it should be declared as an int because it is used as a counter.
    Thank you for your help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. User-defined message problem in MFC dialog-based app
    By jrohde in forum Windows Programming
    Replies: 1
    Last Post: 01-17-2010, 10:08 PM
  2. Strange string behavior
    By jcafaro10 in forum C Programming
    Replies: 2
    Last Post: 04-07-2009, 07:38 PM
  3. socket message sending and receiving problem
    By black in forum C Programming
    Replies: 5
    Last Post: 01-15-2007, 04:46 AM
  4. Request for comments
    By Prelude in forum A Brief History of
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. Staticly Bound Member Function Pointers
    By Polymorphic OOP in forum C++ Programming
    Replies: 29
    Last Post: 11-28-2002, 01:18 PM