Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!hao!oddjob!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Allocation for pointers Message-ID: <8407@mimsy.UUCP> Date: Fri, 4-Sep-87 10:56:35 EDT Article-I.D.: mimsy.8407 Posted: Fri Sep 4 10:56:35 1987 Date-Received: Sat, 5-Sep-87 20:36:48 EDT References: <1357@faline.bellcore.com> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 96 In article <1357@faline.bellcore.com> gtchen@faline.bellcore.com (George T. Chen) writes: >main() >{ char *a; > a = "text"; > recurs(a); >} > >void recurs(a); >char *a; >{ strcat(a,"more text"); > if (some conditional test) recurs(a); >} This will not work (aside from the syntax error and the type clash at the definition of `recurs'). >As I understand it, I'm passing the address of the variable a into >the routine recurs. No, to do that, you must say `recurs(&a)'. You are passing the value of a to the routine recurs; you have claimed that this value points to zero or more characters (`char *a'), which it does indeed. We just covered this one: The value passed from main is the address of the first element of an anonymous array of five characters which is initialised to {'t', 'e', 'x', 't', '\0'}. >At no point do I specify how large of a buffer a will eventually >point to. At no point do you specify a buffer! (For one thing, there is no `buffer' construct *per se* in C, although `array N of char' where N is `large' is conventionally called a buffer.) You made `a' point to this anonymous array of five characters, then told strcat to write over a[4] with 'm', a[5] with 'o', a[6] with 'r', and so forth. >Is there a limit Certainly: The array to which `a' points contains only five slots. >and is it compiler dependent? The result of writing nonexistent array elements is certainly compiler (and runtime system) dependent! You can, instead, pick your own limit: void recurs(); main(...) { char a[LIMIT]; (void) strcpy(a, "text"); recurs(a); ... } recurs(a) char *a; { (void) strcat(a, "more text"); if (...) recurs(a); } or (to save a tiny bit of space and time) main(...) { static char a[LIMIT] = "text"; ... or you can come up with fancy dynamic allocation routines: struct string { char *s_addr; /* address of text */ int s_len; /* current length */ int s_space; /* and space remaining */ }; struct string *string_append(); #define APPEND(result, app) \ ((result)->s_space < (app)->s_len ? string_append(result, app) : \ ((result)->s_len += (app)->s_len, \ (result)->s_space -= (app)->s_len, \ bcopy((app)->s_addr, (result)->s_addr, (app)->s_len), \ result)) or whatnot. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7690) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris