Finding Available Length Of Strings...

Jody Hagins hagins at gamecock.rtp.dg.com
Sun Nov 11 04:53:08 AEST 1990


In article <16758 at hydra.gatech.EDU>, gt4512c at prism.gatech.EDU (BRADBERRY,JOHN L) writes:
|> Just a note of clarification here...I am talking about a character array
|> and I am looking for a solution (not the obvious '...add another length
|> parameter')...I would like the function to be able to 'figure it out!'
|> 
|> Thanks again!
|>   
|> -- 
|> John L. Bradberry        |Georgia Tech Research Inst|uucp:..!prism!gt4512c
|> Scientific Concepts Inc. |Microwaves and Antenna Lab|Int : gt4512c at prism
|> 2359 Windy Hill Rd. 201-J|404 528-5325 (GTRI)       |GTRI:jbrad at msd.gatech.
|> Marietta, Ga. 30067      |404 438-4181 (SCI)        |'...is this thing on..?'   


There are several ways to do this.

1.

typedef struct
    {
    int		size;	/* Alternatively, this could be the last address */
    char *	s;
    } string_t;


void strinit(string_t *sp, char *cp, int size)
{
    sp->s = cp;
    sp->size = size;
}


main()
{
    char	some_var[SOME_SIZE];
    string_t	string;

    strinit(&string, some_var, SOME_SIZE);

    ...
}

Whenever you want to use the C string functions, send string->s.
If you want to use your own, send &string and access both start address
and the length.


2.

#define DEFINED_EOS	((char)1)	/* Any char you can guarantee not in a string */
#define FILL_CHAR	'\0'		/* Any char except DEFINED_EOS */

char *strinit(char *s, int size)
{
    int		i;

    for(i=0; i<size; i++)
        s[i] = FILL_CHAR;
    s[SIZE] = DEFINED_EOS;
    return(s);
}

int defined_strlen(char *s)
{
    int		i=0;

    while (*s++ != DEFINED_EOS)
        i++;
    return(i);
}

main()
{
    char	s[SOME_SIZE+1];		/* For this implementation, you will need one
					   extra byte to store the defined-end-of-string
					   location.  Otherwise, it could get overwritten
					   by '\0'. */

    strinit(s, SOME_SIZE);

    ...

}

Now, the C routines work, and you can get the defined length of any
string by calling defined_strlen(s).



Hope this helps.

Jody Hagins
hagins at gamecock.rtp.dg.com



More information about the Comp.lang.c mailing list