
pointers in scanf and printf
Quote:
>> i'm using the newest version of the djgpp compiler (gcc ported to
>windows).
>> the problem is this...when i do
>> int main(void)
>> {
>> char *name;
>This defines a pointer to char. It doesn't define where that pointer is
>pointing, and it doesn't allocate any memory.
It allocates memory for the pointer itself but, say you say, nothing for
it to point at.
Quote:
>> scanf("%s",name);
>So this statement overwrites some random lump of memory. Bad news.
As the most basic level it is reading the value of name which at this
point is an uninitialised variable. Reading the value of an uninitialised
variable is always an error, whether it be a pointer or not.
Quote:
>> printf("%s\n",name);
>> }
>> it doesn't work. it keeps giving me a gpf, but,
>> int main(void)
>> {
>> char *name;
>> scanf("%s",&name);
>> printf("%s\n",&name);
>> }
>> does work.
>Purest fluke. The code is no more correct than in the first program.
>Slightly less correct, if anything.
Well, the only things that *might* be viewed as less correct than
undefined behaviour are syntax errors and constraint violations and
this is neither of those. There is more chance of this working than
the first version on platforms that use the same representation for
all data pointers and where the input string is small: at least
the address sof a valid object is being passed and the string
is written into that.
Quote:
> when &name is used, isn't the address of the pointer being
>> passed?
>Yes.
>> it seems to me that we would just want to pass the pointer,
>Yes.
>> the the
>> functions can just loop through and increment the pointer to access each
>> element.
>Yes.
>> even more baffeling (to me anyway) is that the second version only
>> works if 7 or fewer characters used. when you try it with 8 characters,
>it
>> gives me a gpf. am i overlooking something? is this just a stupid
>mistake?
>Yes. :-)
>> please help!!! thanks.
>Okay. Reserve some space for your string. Here's an example that uses a
>more robust input function as well as correctly using memory:
>#include <stdio.h>
>int main(void)
>{
> char name[64]; /* Most people's names are shorter than 64. */
> printf("Please type in your name: ");
> fflush(stdout);
> if(fgets(name, sizeof name, stdin) != NULL)
> {
> printf("You typed [%s]\n", name);
This will produce odd output for "short" names since name will
contain a new-line character.
Quote:
> }
> else
> {
> printf("The man with no name? I've always wanted to meet you.\n");
> }
> return 0;
>}
--
-----------------------------------------
-----------------------------------------