Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

c++ - Different answers from strlen and sizeof for Pointer & Array based init of String


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because sizeof gives you the size in bytes of the data type. The data type of str1 is char* which 4 bytes. In contrast, strlen gives you the length of the string in chars not including the null terminator, thus 7. The sizeof str2 is char array of 8 bytes, which is the number of chars including the null terminator.

See this entry from the C-FAQ: http://c-faq.com/~scs/cclass/krnotes/sx9d.html

Try this:

 char str2[8];
 strncpy(str2, "Sanjeev", 7);
 char *str1 = str2;
 printf("%d %d
",strlen(str1),sizeof(str1));    
 printf("%d %d
",strlen(str2),sizeof(str2));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...