0

Very simple C printing question!

#include <stdio.h>
#include <conio.h>
int main() {
   int Age = 0;
   printf("Enter your Age\n");
   scanf("%d",&Age);
   char Name;
   printf("Enter your Full name\n");
   scanf("%s",&Name);
   printf("My name is %s and I am aged %d" ,&Name,Age);
return 0;
}

When I input "blah" and 1, for some reason this returns: "My name is Blah and I am aged 1929323232"

I presume I am misunderstanding a data format in either the scanf or the printf functions but can't work it out.

1
  • 4
    If you actually inspect the value returned from scanf(), you might start to understand the problem. Oh, and turn on compiler warnings. You need to reserve space for more than one char if you're using %s. Commented Oct 10, 2019 at 14:37

1 Answer 1

4

The problem is because of line

char Name;

Name is of type char. That means that it is supposed to store only one character. As a result
1. The scanf() is not able to store the input text properly (this will result in a crash in most cases or other undefined behaviour depending on the system - which judging by the output you provided is what you got)
2. (if the code didn't crash) Treating Name as a string with the %s argument in printf() essentially outputs garbage.

The type that corresponds to strings in C is char * (or char[]). Essentially, changing Name to some statically allocated char-array while performing the necessary changes in the next lines should fix your error:

char Name[256]; //allocated 256 bytes in Name array
printf("Enter your Full name\n");
scanf("%s",Name); // removed & before Name
printf("My name is %s and I am aged %d" ,Name,Age); // same here

You could also opt to go with a dynamically allocated string of type char * but I guess that's a different topic altogether.

As a general suggestion, I think you should look at pointers more closely. Especially in C, almost all string operations involve being aware of pointer mechanisms.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.