Path: utzoo!utgpu!water!watmath!clyde!motown!vilya!lcuxlm!whuts!att!ucbvax!IMAX.ENG.UIOWA.EDU!timv
From: timv@IMAX.ENG.UIOWA.EDU (Tim VanFosson)
Newsgroups: comp.sys.apollo
Subject: String copy problem
Message-ID: <8808181348.AA21184@imax.eng.uiowa.edu>
Date: 18 Aug 88 13:48:53 GMT
Sender: daemon@ucbvax.BERKELEY.EDU
Organization: CAD-Research, University of Iowa
Lines: 47


   >> I don't understand why following codes don't work:
   >> #include 
   >> #include 
   >> main(argc, argv)
   >> int      argc;
   >> char    *argv;
   >> {
   >> char    *str1;
   >> strcpy(str1, argv[1]);
   >> }
   >
   >This is not a problem with the apollo, but a problem with your understanding
   >of pointer syntax. Relax, it's a common mistake! The definition
   >
   >     char *str1:
   >
   >means "str1" is a POINTER to an array of characters. In other words, str1
   >is supposed to contain the address of a character array. But in this code
   >fragment, you have not assigned an address to "str1", so the variable contains
   >a "garbage" address. Therefore, when the program tries to run, it tries to copy 
   >the string pointed to by argv[1] to a non-existant character array. This is
   >why you get an "access violation". The way to fix this would be to define
   >str1 like this:
   >
   >    char str1[255]; 
   >(or replace the 255 with some number more appropriate to your application)
   >so that there is an array defined for strcpy to copy into. 

      You could also use malloc to allocate space for the string, i.e.,

           str1 = (char *)malloc( sizeof( *argv[1] ));

   >
   >I would suggest that you get a good book on basic C programming before you 
   >go any further. I don't know of any offhand, but there *are* some good books
   >out there that would help you avoid the more common C mistakes.
   >

         You might try _The C Programming Language_ by Kernighan and
      Ritchie, published by Prentice-Hall.  It is considered to be
      *the* C reference (one company shipped it to us as documentation :-) ).
---
Timothy VanFosson                           Internet : timv@imax.eng.uiowa.edu
Systems Analyst                             US Mail  : CAD-Research
University of Iowa                                     1405 Engineering Building
Phone : (319) 335 - 5728                               Iowa City, Iowa 52242