Scoping question in C

billt-lxSQFCZeNF4 at public.gmane.org billt-lxSQFCZeNF4 at public.gmane.org
Mon Jun 13 20:16:07 UTC 2005


On Mon, Jun 13, 2005 at 03:02:52PM -0400, Henry Spencer wrote:
> On Mon, 13 Jun 2005, Taavi Burns wrote:
> > But what if the source string is (somehow) not NULL-terminated!  ;)
> > Given a source string of unknown size...
> 
> If you don't know how long it is, there's really not much you can usefully
> do with it.  You *have* to have either NUL termination or a known length. 
> Just copying some arbitrary number of characters into a buffer is neither
> safe nor reliably useful.
> 
It is possible to count the number of characters until a NUL is found, then allocate memory for that length and copy it to the allocated memory and return that memory. Just remember to deallocate the memory.

x=0;
while ( string[x] != 0 ) { x++; }
y= malloc(sizeof(char)*(x+1) );
stcpy (string, y);

Note there is no guarentee the program is correct or works.

Bill
--
The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml





More information about the Legacy mailing list