So I'm working on a documentary of learning the C Language and I want to make examples within pointers and input. Basically, I made a Hello, (name).
program like this using C99:
#include <stdio.h>
int main() {
char *name;
printf("What's your name? ");
scanf("%s", name);
printf("Hello, %s.\n", name);
}
When I tried compiling it, the error it gave me was this:
C3.c:5:48: error: variable 'name' is uninitialized when used here [-Werror,-Wuninitialized]
printf("What is your name? "); scanf("%s", name);
^~~~
C3.c:4:17: note: initialize the variable 'name' to silence this warning
char *name;
^
= NULL
1 error generated.
<builtin>: recipe for target 'C3' failed
make: *** [C3] Error 1
So I modified line 2 into char *result = "";
, which actually worked this time, but the output was this:
What's your name? Bro
Segmentation fault
This is a little confusing for me, since I'm not actually used to the scanf()
function.
So my problem is, what would be a better way to get strings by input using scanf()
in C99 without any weird output right after?