Sato Sato - 2 months ago 8
C Question

C program doesn't print text when trying to access string data using pointers

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.

Answer
int readMessage(char msg[]){
    int i;
    for(i = 0; (*msg = getchar()) != '\n'; i++);
    return i;
}

Each character is assigned to *msg (equivalently to msg[0]). The msg pointer is never updated and never indexed by i, so you never assign values to the remaining characters in the array whose initial element is pointed to by msg.

Replacing *msg by msg[i] is one partial solution. Note that this still doesn't write a null '\0' terminator into msg, so the msg array does not contain a string. But since your printMessage function doesn't require a string (it takes a len argument), that's not strictly necessary. Still, if you're going to operator on the array in other ways, it's probably a good idea to null-terminate it.

Comments