You've declared str
as a pointer, but you haven't given it a valid location to point to; it initially contains some random value that may or may not be a writable memory address. You still need to allocate a block of memory large enough to hold your input, either by declaring an array or by allocating memory with malloc
or calloc
.
Secondly, the %s
conversion specifier expects the corresponding argument to have type char *
; since str
has that type, you don't need to use the &
operator.
So, you'll need to do something like
char str[SOME_SIZE];
or
char *str = malloc( SOME_SIZE );
where SOME_SIZE
is large enough to hold the string you enter plus one extra character for the 0 terminator.
You'd read and write the input as follows:
scanf( "%s", str );
printf( "%s", str );
You don't need the &
for either call. The %s
conversion specifier expects the corresponding argument to have type char *
. Under most circumstances1, an expression of array type is converted to an expression of pointer type, and the value of the expression is the address of the first element in the array. If you declared str
as an array, then in the scanf
and printf
calls the expression str
2 will be converted to a char *
. If you declared str
as a char *
, it's already the expected type.
Now, output is (typically) line-buffered, meaning it won't show up on your console unless there's a newline or the length of the string exceeds the buffer length. You will either want to add a newline to your print statement:
printf( "%s\n", str );
or call fflush
on the standard output stream:
printf( "%s", str );
fflush( stdout );
to make sure your output gets displayed.
1 - The exceptions to this rule occur when the array expression is the operand of the sizeof
. _Alignof
, or unary &
operators, or is a string literal being used to initialize another array in a declaration.
2 - Remember, this conversion operation applies to expressions, not objects. You'll occasionally hear someone claim that "arrays are pointers", but this isn't true; arrays and pointers are different animals completely.