-4

I'm a newbie learning to program in C, and I am currently working on creating a program that takes a name input from a user then prints that name back on to the screen. When the program prints out the name in the else if block, what I get is $ ". I want to know why it happens and how I might correct this problem. My code is as follows:

#include <stdio.h>
#include <stdlib.h>
int main() {
    char * ans; // yes/no answer
    char * name; //name variable

    printf("Welcome to the program. Would you like to begin? (y/n)\n");
    scanf("%s", ans);

    if (strcmp(ans, "y") != 0) {
        printf("Have a good day!\n");
        return 0;
    }
    else if (strcmp(ans, "y") == 0)
        printf(" %s\n", ans);

    printf("Okay, input your name:\n");
    scanf("%s", name);

    printf(" %s", name);// I get $ " rather than the name.

    return 0;
}
Barry
  • 3,303
  • 7
  • 23
  • 42
  • 1). Do you know what a Pointer is? 2). You do know that ans and name are pointers? 3). You do not need help, you need a Good C book. – Michi Jun 03 '16 at 08:20

1 Answers1

2

You are using scanf() to read characters from the user, but haven't allocated any memory to hold those characters. This gives undefined behavior, as "anything can happen" when you break the rules like that.

Make those uninitialized pointers into arrays instead:

char ans[128];
char name[128];

This gives you 128 characters of space for each string (one of which will be used by the terminator).

unwind
  • 391,730
  • 64
  • 469
  • 606