Finding Available Length Of Strings...

Blair P. Houghton bhoughto at cmdnfs.intel.com
Sun Nov 11 06:25:48 AEST 1990


After much email, John's got the picture. (Hint.)

In article <14411 at smoke.brl.mil> gwyn at smoke.brl.mil (Doug Gwyn) writes:
>In article <16752 at hydra.gatech.EDU> gt4512c at prism.gatech.EDU (BRADBERRY,JOHN L) writes:
>>When passing strings to other functions, what is the BEST way to find
>>the bytes remaining in the formal string parameter (to prevent over-
>
>What on earth do you mean?  You don't pass strings to C functions; the
>best you can do is pass pointers to arrays containing chars.  There is
>no way to determine in the called function where the end of the array
>allocation might be, given merely a pointer into it.

"pointers to arrays containing chars"?

    typedef char A[SIZE];
    ...
	A *foo;
	...
	func(foo);


    func( A *bar )	/* bar points to array of chars */
    {
	printf( "%d\n", sizeof (*bar) );
    }

Note, however, that foo may not point to an arbitrary
string (unless you're careful to put all your strings in
these arrays).  Note also that we're not really using an
arbitrary string, but only one that's stored in an
array SIZE of char.  Note also that, since it is a pointer
to an array rather than a pointer to char, you have to get
the chars through `*foo[i]' or `**foo' rather than `*foo'
or `foo[i]'.

The most important thing to note is that `func()' *knows*
the size of the array.  You have compiled it in.  This
defeats certain purposes.

The usual convention for "passing strings" is to pass a
pointer to the first character of the array rather than a
pointer to the array.  This depends on the fact that you've
stored the string as chars in contiguous memory locations
and on the assumption that the last character of the string
is a '\0'.  This is also how strings are handled in all of
the library functions and system calls you're likely to
encounter.  It provides flexibility; otherwise, all strings
would have a minimum storage allocation and a maximum
length (although, technically, with the current convention
the minimum usable is one char ('\0'), and certain features
of systemic i/o often lead one to limit the SIZE
consistently to BUFSIZ...)).

The only reason you should want the size of the array a
string is stored in is if you are at some point more
interested in the array than the string (as is fgets(),
for example, which of course asks for a pointer to the
first character's location and for the size).

				--Blair
				  "Did I hear an 'oops'?"



More information about the Comp.lang.c mailing list