Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!uwm.edu!uwvax!rang From: rang@cs.wisc.edu (Anton Rang) Newsgroups: comp.lang.c Subject: Re: Help... Message-ID: Date: 10 Oct 89 02:56:08 GMT References: <731@carroll1.UUCP> <39902@bu-cs.BU.EDU> Sender: news@spool.cs.wisc.edu Organization: UW-Madison CS department Lines: 51 In-reply-to: austin@bucsf.bu.edu's message of 10 Oct 89 02:07:14 GMT In article <39902@bu-cs.BU.EDU> austin@bucsf.bu.edu (Austin Ziegler) writes: >dnewton@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 >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@cs.wisc.edu | | University of Wisconsin--Madison | | +----------------------------------+------------------+