Help...

Anton Rang rang at cs.wisc.edu
Tue Oct 10 12:56:08 AEST 1989


In article <39902 at bu-cs.BU.EDU> austin at bucsf.bu.edu (Austin Ziegler) writes:
>dnewton at carroll1.UUCP (Dave 'Yes, I'm weird' Newton) said:
>Dave> Relay-Version: version B 2.10.3 4.3bds beta 6/6/85; site bu-cs.BU.EDU
>Dave> Date-Received: 10 Oct 89 01:39:31 GMT
>
>Dave> Why doesn't this work?
>
>Dave> ==========================
>Dave> #include <stdio.h>
>Dave> main ()
>Dave> {
>Dave>    char      h[];
>Dave>    scanf ("%s", h);
>Dave>    printf ("%s\n", h);
>Dave> }
>Dave> ==========================
>
>Dave>   It seems innocent enuf, but just prints garbage.  I'm missing something
>Dave> obvious, but I'll be darned if I know what it is.
>
>    I don't know [ ... ] you can get the same
>result from char *h, and not get too many problems.

[ This is not a flame, just a clarification, OK? ]

There is no difference between "char h[]" and "char *h" in a
declaration; they do exactly the same thing.  This program fails
because there is no storage allocated for the string.

  The "char h[]", or "char *h", declares a *pointer* to a character
array.  It doesn't allocate any storage space for the array, though.
"scanf" happily uses the random contents of the pointer, which may
well point onto the stack, into unwritable locations, etc.  In the
best case, this would generate a run-time error.

  You need to either allocate an array:

	char h[80];

  or allocate a pointer, and then space for an array:

	char *h, *malloc();

	h = malloc(80);

  Either one of these techniques will work.
   
+----------------------------------+------------------+
| Anton Rang (grad student)        | rang at cs.wisc.edu |
| University of Wisconsin--Madison |                  |
+----------------------------------+------------------+



More information about the Comp.lang.c mailing list