In
A simple code won't work:
#include <stdio.h>
This reserves storage for one byte of memory - i.e. sufficient to
store a single character. If you want to store a string there, bear
in mind that you will need one byte for a null terminator. That
doesn't leave any room at all for actual data.
printf("Enter your name: ");
How many people do you know whose name is 0 characters long?
scanf doesn't know that you've only got one byte available. It will
accept the character pointer *as if* it pointed to an area of memory
sufficiently large to accept any amount of data the user cares to
provide.
printf("Your name is: %s\n",a);
it says:
warning: format ?%s? expects type ?char *?, but argument 2 has type
?int?
a is a char. C has rules for promoting data types, and in this
instance the char is being promoted to int, which is why the compiler
says what it says.
What you actually need is an *array* in which to store the name:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME_LEN 256
int main(void)
{
int rc = EXIT_SUCCESS;
char name[MAX_NAME_LEN + 1] = {0};
printf("Enter your name (max %d characters).\n", MAX_NAME_LEN);
if(fgets(name, sizeof name, stdin) != NULL)
{
printf("Your name is %s\n", name);
}
else
{
fprintf(stderr, "Error reading name.\n");
rc = EXIT_FAILURE;
}
return rc;
}
--
Richard Heathfield <
http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within