sizeof "string" and embedded nulls

hansen at pegasus.UUCP hansen at pegasus.UUCP
Sat Feb 4 00:56:37 AEST 1984


	Is "Hello\0, world." a string, or is it two strings?
	Put another way, is '\0' a legal character to embed
	within a string?

I'd say that all depends on how you define a 'string'. K&R (page 181)
defines:

	A string is a sequence of characters surrounded by double quotes, as
	in "...". A string has type "array of characters" ... and is
	initialized with the given characters. ... The compiler places a null
	byte \0 at the end of each string so that programs which scan the
	string can find its end.

By this definition "Hello\0, world." is a perfectly valid single string and
has a length of 15 characters.

However, if I look in my UNIX manual (System V) under string(3), I see:

	The arguments s1, s2 and s point to strings (arrays of characters
	terminated by a null character).

By this definition, "Hello\0, world." is also a perfectly valid string, but
this time has a length of only 6 because the null character has terminated
it there.

It all depends on your context as to what you want to consider it as. In
this example,

    char string[] = "Hello\0, world.";
    write(1,string,strlen(string));
    write(1,string,sizeof(string));

the two writes won't produce the same answer. In most PRACTICAL cases, it
will.

In either case, it is still a single string.

					Tony Hansen
					pegasus!hansen
					AT&T-IS



More information about the Comp.lang.c mailing list