I'm going through "C Programming: A Modern Approach" by K.N. King right now. This program is taken from "Section 12 - Pointers and Arrays", Project 1b. Roughly, the goal is: Write a program that reads a message, then prints the reverse of the message. Store the message in an array, and keep track of the current position in the array using a pointer.
Currently, I'm just trying to get the message to print normally before I try and make it print backwards. I'm frustrated because my printMessage() function is 1:1 with the print_message() function from here, however when the program is run and some text is entered, it just prints out a blank line. This happens if the line within the for-loop of printMessage() is changed to 'printf("%c", *p);' as well.
Here is my code:
#include <stdio.h>
#define MAX_MESSAGE_LENGTH 100
int readMessage(char msg[]);
void printMessage(char msg[], int len);
/* finish later
void printMessageReversed(char msg[], int len); */
int main(void){
int msg_length;
char c[MAX_MESSAGE_LENGTH];
printf("Enter a message: ");
msg_length = readMessage(c);
printf("Length: %d", msg_length);
printf("\nMessage: ");
printMessage(c, msg_length);
return 0;
}
int readMessage(char msg[]){
int i;
for(i = 0; (*msg = getchar()) != '\n'; i++);
return i;
}
void printMessage(char msg[], int len){
char *p;
for(p = msg; p < msg + len; p++){
putchar(*p);
}
}
Wondering if anyone can help identify my problem? I'm sure it's something painfully obvious or naive that I'm just missing. Thanks for any help.
msgparameter is a pointer.nulterminator at the end of the input to make the array a "string", inreadMessage