home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!dtix!darwin.sura.net!convex!egsner!dalnet!u2u!bob.calbridge
- From: bob.calbridge@u2u.lonestar.org (Bob Calbridge)
- Newsgroups: comp.lang.c
- Subject: Help! what's wrong with this program?
- Message-ID: <2576.217.uupcb@u2u.lonestar.org>
- Date: 8 Sep 92 23:07:00 GMT
- Reply-To: bob.calbridge@u2u.lonestar.org (Bob Calbridge)
- Organization: USER-TO-USER PCBoard (214)492-6565 (USR DS v32bis)
- Lines: 53
-
- To: zzang@whale.uucp (Zhuo Zang[~{j0WA~}])
- Message-ID: <1992Sep6.041410.16388@eng.ufl.edu>
- Date: Sun, 6 Sep 92 04:14:10 GMT
-
- ZZ> Hello,
- ZZ> I try to push char c onto buf, and then
- ZZ> print out the buf.
- ZZ> But the following codes don't work.
- ZZ> After compilation, I use
- ZZ> > foo <foo.c
- ZZ> nothing printed out.
-
- ZZ> Could someone tell me why ?
-
- ZZ> Thanks in advance !
- ZZ> --------- foo.c ----------
- ZZ> #include <stdio.h>
- ZZ> char *sp, buf[BUFSIZ], c;
- ZZ> main()
- ZZ> {
- ZZ> sp = buf;
- ZZ> while ((c=getchar())!=EOF) pushc(c,sp);
- ZZ> *sp = '\0';
-
- ZZ> puts(buf);
- ZZ> return;
- ZZ> }
-
- ZZ> pushc(char c, char *bp)
- ZZ> {
- ZZ> *bp++ = c;
- ZZ> return;
- ZZ> }
-
- Confusion between what you're passing and what is really being affected.
- The char *bp in your function is a local variable and regardless of what
- happens to it when the function is executed does nothing to affect the
- value of the variable that was passed to it. In essence, when you
- "bp++" the value of "sp" in main() doesn't change so you keep passing
- the value of buf on each iteration. As a consequence bp keeps
- { obtaining the value of buf and gets incremented} over and over again.
- sp never changes. You need to either
-
- 1) declare a global variable as your pointer and use it in main
- and the function.
- 2) skip using pushc() and simply use a pointer in main and
- manipulate it within main().
- 3) do something more complex by making bp a static variable and
- modifying the function to accept an action flag to set the
- pointer to a passed value.
-
- * SLMR 2.1 * hAS ANYONE SEEN MY cAPSLOCK KEY?
-
-