total space of a string

Ken Poe poek at psu-cs.UUCP
Fri Dec 30 10:45:23 AEST 1988


In article <29 at rpi.edu> > kyriazis at rpics (George Kyriazis) writes:

>In article <1827 at solo11.cs.vu.nl> maart at cs.vu.nl (Maarten Litmaath) writes:
>>barmar at think.COM (Barry Margolin) writes:
>>\1) When I've done this in other languages, I've used something like
>>\strlen("/") instead of the 2.  Unfortunately, in C I'd still have to
>>\say "+1", ....
>>
>>How about the following?
>>
>>	sizeof "/"
>
>"/" is a pointer to a string containing a '/' and a '\0'.  Therefore
>it seems to me that sizeof "/" will return the same value as 
>sizeof( char * ).  
>Comments??

	Only if your system has 2 byte pointers.

	The sizeof operator in C returns the size of the object (or of 
	any object of that type for size of a type).  When the object 
	is a "string" (actually an array of char), the sizeof operator
	returns the number of bytes in the array. (including the null
	character ('\0') at the end of the "string") 

	Try the following:

		main()
		{
			static char string[] = "abcd";
			/* null char appended to string constants by the compiler */

			printf("The size of string is %d\n", sizeof(string) );
			printf("The size of \"/\" is %d\n", sizeof "/");
			printf("The size of (char *) is %d\n", sizeof (char *) );
		}

	On the VAX it's output is:

		The size of string is 5
		The size of "/" is 2
		The size of (char *) is 4

	The only thing that is implementation dependent is the size of
	a pointer (32 bits on most systems) which can be 2 bytes.  (near
	pointers in MSC etc).

-- 
   Kenneth N. Poe ATP, CFI  |  ARPANET: poek%cs.pdx.edu at relay.cs.net
   16925 N.E Glisan St.     |  CSNET:   poek at cs.pdx.edu
   Portland OR  97230-6252  |  UUCP:    {ucbvax,uunet,gatech}
   voice: (503) 252-1191    |             !tektronix!psu-cs!poek
   cu:    (503) 254-1009    |  C-SERVE: 73477,2452 
   (when I get it working)

    ----------------------------------------------------------------------  
    I would much rather be on the ground wishing I were in the air than
    to be in the air wishing I were on the ground.  --  Ken Poe
    ----------------------------------------------------------------------  



More information about the Comp.lang.c mailing list