Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

strlen() function 1

Status
Not open for further replies.

yasin007

Programmer
Oct 14, 2003
13
SG
Hi , i have tried this following code

unsigned char xx[2] = "ab";
printf("%d\n\n",strlen(xx));

it prints 15 . I thought , it will be 2 .

How strlen() is working ?


Iam new for C and came from Java.Any help higly appreciated.



 
> How strlen() is working ?
strlen() works by finding a \0 character

> unsigned char xx[2] = "ab";
This does NOT have a \0 character, so strlen() just wanders through memory until it finds one, or the OS steps in and kills your program.

unsigned char xx[3] = "ab";
is what you need as a minimum

unsigned char xx[30] = "ab";
initialises the first 2 chars to ab, and the other 28 to \0

unsigned char xx[] = "ab";
reserves just enough space for the string, and a \0


--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top