Re: Help with code

From: Jamie Squires (squires@adelphia.net)
Date: 11/25/02


> char *map_repl(char *c, size_t pos, int chr) {
>   char buf[8000];
>   size_t i;
>
>   for (i=0; i<strlen(c); i++) {
>     if (i==pos)
>       buf[i] = chr;
>     else
>       buf[i] = c[i];
>   }
>   buf[i]='\0';
>   c = buf;
>   return c;
> }
>
> int main() {
>   char *map[] = {
>     "-----\r\n",
>     "-----\r\n",
>     "-----\r\n"
>   };
>
>   map[0] = map_repl(map[0],2,'a');
>   printf("%s",map[0]);
>   return 0;
> }

Unfortunately, this won't work because buf is only accessible within the
scope of the map_repl function.  Once you return from map_repl, the memory
allocated for buf is freed.  Your example may appear to work, but that is
only because the memory occupied by buf has not yet been overwritten by
something else.  If you really need variable-length strings, you may want to
look into dynamically allocating them with malloc.

Jamie

--
   +---------------------------------------------------------------+
   | FAQ: http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html |
   | Archives: http://post.queensu.ca/listserv/wwwarch/circle.html |
   | Newbie List:  http://groups.yahoo.com/group/circle-newbies/   |
   +---------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 06/25/03 PDT