home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / c / 13445 < prev    next >
Encoding:
Internet Message Format  |  1992-09-09  |  2.1 KB

  1. Path: sparky!uunet!dtix!darwin.sura.net!convex!egsner!dalnet!u2u!bob.calbridge
  2. From: bob.calbridge@u2u.lonestar.org (Bob Calbridge)
  3. Newsgroups: comp.lang.c
  4. Subject: Help! what's wrong with this program?
  5. Message-ID: <2576.217.uupcb@u2u.lonestar.org>
  6. Date: 8 Sep 92 23:07:00 GMT
  7. Reply-To: bob.calbridge@u2u.lonestar.org (Bob Calbridge)
  8. Organization: USER-TO-USER PCBoard (214)492-6565 (USR DS v32bis)
  9. Lines: 53
  10.  
  11. To: zzang@whale.uucp (Zhuo Zang[~{j0WA~}])
  12. Message-ID: <1992Sep6.041410.16388@eng.ufl.edu>
  13. Date: Sun, 6 Sep 92 04:14:10 GMT
  14.  
  15. ZZ> Hello,
  16. ZZ> I try to push char c onto buf, and then
  17. ZZ> print out the buf.
  18. ZZ> But the following codes don't work.
  19. ZZ> After compilation, I use
  20. ZZ> > foo <foo.c
  21. ZZ> nothing printed out.
  22.  
  23. ZZ> Could someone tell me why ?
  24.  
  25. ZZ> Thanks in advance !
  26. ZZ> --------- foo.c ----------
  27. ZZ> #include <stdio.h>
  28. ZZ> char *sp, buf[BUFSIZ], c;
  29. ZZ> main()
  30. ZZ> {
  31. ZZ>   sp = buf;
  32. ZZ>   while ((c=getchar())!=EOF) pushc(c,sp);
  33. ZZ>   *sp = '\0';
  34.  
  35. ZZ>   puts(buf);
  36. ZZ>   return;
  37. ZZ> }
  38.  
  39. ZZ> pushc(char c, char *bp)
  40. ZZ> {
  41. ZZ>   *bp++ = c;
  42. ZZ>   return;
  43. ZZ> }
  44.  
  45. Confusion between what you're passing and what is really being affected.
  46. The char *bp in your function is a local variable and regardless of what
  47. happens to it when the function is executed does nothing to affect the
  48. value of the variable that was passed to it.  In essence, when you
  49. "bp++" the value of "sp" in main() doesn't change so you keep passing
  50. the value of buf on each iteration.  As a consequence bp keeps
  51. { obtaining the value of buf and gets incremented} over and over again.
  52. sp never changes.  You need to either
  53.  
  54.    1) declare a global variable as your pointer and use it in main
  55.       and the function.
  56.    2) skip using pushc() and simply use a pointer in main and
  57.       manipulate it within main().
  58.    3) do something more complex by making bp a static variable and
  59.       modifying the function to accept an action flag to set the
  60.       pointer to a passed value.
  61.  
  62.  * SLMR 2.1 * hAS ANYONE SEEN MY cAPSLOCK KEY?
  63.                                                                                                                                 
  64.