Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

difference between sizeof and strlen in c


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

1 Reply

0 votes
by (71.8m points)

strlen() is used to get the length of a string stored in an array.

sizeof() is used to get the actual size of any type of data in bytes.

Besides, sizeof() is a compile-time expression giving you the size of a type or a variable's type. It doesn't care about the value of the variable.

strlen() is a function that takes a pointer to a character, and walks the memory from this character on, looking for a null character. It counts the number of characters before it finds the null character. In other words, it gives you the length of a C-style null-terminated string.

The two are quite different. In C++, you do not need either very much, strlen() is for C-style strings, which should be replaced by C++-style std::strings, whereas the primary application for sizeof() in C is as an argument to functions like malloc(), memcpy() or memset(), all of which you shouldn't use in C++ (use new, std::copy(), and std::fill() or constructors).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...