473,398 Members | 2,404 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Sizeof vs. Strlen

hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.
Nov 14 '05 #1
21 8440
sugaray wrote:
hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


#include <stdio.h>
#include <string.h>

int main(void)
{
char s[20] = "hello";
char *ptr = "hello2";

printf("s: sizeof == %u, strlen == %u\n", sizeof s, strlen(s));
printf("ptr: sizeof == %u, strlen == %u\n", sizeof ptr, strlen(ptr));

return 0;
}

--
Thomas.

Nov 14 '05 #2
In <ad**************************@posting.google.com > ru****@sohu.com (sugaray) writes:
hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


strlen is seldom used with a string literal as its argument...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #3
On 27 May 2004 05:52:29 -0700, in comp.lang.c , ru****@sohu.com (sugaray)
wrote:
hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1',
you don't need the -1
so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(void)
{
char* somestr = "hello world";
printf("length is %d or %d\n", sizeof somestr, strlen(somestr));
return EXIT_SUCCESS;
}

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #4
In <ah********************************@4ax.com> Mark McIntyre <ma**********@spamcop.net> writes:
On 27 May 2004 05:52:29 -0700, in comp.lang.c , ru****@sohu.com (sugaray)
wrote:
hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1',
^^^^^^^^^^^^^^you don't need the -1


Of course you do, when using the sizeof operator in the OP's context,
and if you want to get the same result as from strlen(S). Then again,
Mark McIntyre is not supposed to understand this...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #5
sugaray wrote:

hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


sizeof () gives the total storage size of the string
(including the '\0' terminating character)
and is evaluated at compile time. It's argument
(and the resultant value) can never change at run-time.

strlen() gives the length, excluding the '\0'
terminating character, of the string, and is
evaluated at run-time. It's argument, a pointer
to char array, can change at run-time (as well
as the items in the array itself).

Stephen
Nov 14 '05 #6
sugaray wrote:
hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


Strlen is useful for non literal string.

#include <stdio.h>
#include <string.h>
#define STRING "Hello World!"
#define PRINT(S) printf("%s sizeof == %2u, strlen == %2u\n", \
S, sizeof(S), strlen(S));
int main(void)
{
char s[50] = STRING;
char *p = STRING;
PRINT(STRING);
PRINT(s);
PRINT(p);
return 0;
}

Compiled and executed on my machine will output:

Hello World! sizeof == 13, strlen == 12
Hello World! sizeof == 50, strlen == 12
Hello World! sizeof == 4, strlen == 12

- Dario
Nov 14 '05 #7
sugaray wrote:

hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


You answered your own question. It only works string literals or arrays
that are occupied by a string that exactly fills them (including
terminator). Arrays that contain strings shorter than their capacity,
dynamically allocated string buffers, or any string that has been
assigned to a pointer or passed in to a function won't work.


Brian Rodenborn
Nov 14 '05 #8
sugaray wrote:
hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


You are very confused. Consider the following program. Does 'sizeof'
help in any way in determining the length of the string?

#include <stdio.h>
#include <string.h>

int main(void)
{
char foo[BUFSIZ] = "crap";
char *bar = foo;
printf("When bar points to foo containing \"%s\",\n"
" sizeof foo = %lu, strlen(foo) = %lu\n"
" sizeof bar = %lu, strlen(bar) = %lu\n\n",
foo,
(unsigned long) sizeof foo, (unsigned long) strlen(foo),
(unsigned long) sizeof bar, (unsigned long) strlen(bar));
strcpy(foo, "bananas");
printf("When bar points to foo containing \"%s\",\n"
" sizeof foo = %lu, strlen(foo) = %lu\n"
" sizeof bar = %lu, strlen(bar) = %lu\n\n",
foo,
(unsigned long) sizeof foo, (unsigned long) strlen(foo),
(unsigned long) sizeof bar, (unsigned long) strlen(bar));
return 0;
}
When bar points to foo containing "crap",
sizeof foo = 16384, strlen(foo) = 4
sizeof bar = 4, strlen(bar) = 4

When bar points to foo containing "bananas",
sizeof foo = 16384, strlen(foo) = 7
sizeof bar = 4, strlen(bar) = 7
Nov 14 '05 #9
In article <40**************@boeing.com.invalid>,
Default User <fi********@boeing.com.invalid> wrote:
sugaray wrote:

hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


You answered your own question. It only works string literals or arrays
that are occupied by a string that exactly fills them (including
terminator). Arrays that contain strings shorter than their capacity,
dynamically allocated string buffers, or any string that has been
assigned to a pointer or passed in to a function won't work.


On most implementations, sizeof ("Hello, world!") - 1 != 13. Usually the
result will be 3 or 7.
Nov 14 '05 #10
Christian Bau wrote:

On most implementations, sizeof ("Hello, world!") - 1 != 13. Usually the
result will be 3 or 7.


You're saying "most implementations" are broken, then?
Every C implementation I have ever used would get this one
right -- but then, I've used only a small minority of all
C implementations.

--
Er*********@sun.com

Nov 14 '05 #11
ru****@sohu.com (sugaray) wrote in message news:<ad**************************@posting.google. com>...
hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


The difference is that sizeof is compile time operator, so you can get
length of only "string literlals" rather than "strings" in general.
While your strlen is a function that is called at runtime.

strlen is a general function capable of computing the length of any
string. It could be used against your "manufactured"/"malloced"
strings as effeciently as against string literals or char arrays,
while sizeof can only be used against your string literals.
I would go with sizeof() as it won't involve any runtime costs.

--
Imanpreet Singh Arora
isingh AT acm DOT org
Nov 14 '05 #12
Christian Bau wrote:
On most implementations, sizeof ("Hello, world!") - 1 != 13. Usually the
result will be 3 or 7.


I think you are wrong. Please present some evidence of this. You ARE
aware that sizeof is an operator, not a function?
Here's a test program:

#include <stdio.h>

int main(void)
{
printf ("%u\n", (unsigned int) (sizeof ("Hello, world!") - 1));
return 0;
}
Built and run with Visual Studio:

13
Press any key to continue
Built and run with gcc:

hercules:/home/m196957> gcc -o so so.c
hercules:/home/m196957> ./so
13
I can't imagine how anything else would be produced.

Brian Rodenborn
Nov 14 '05 #13
Christian Bau <ch***********@cbau.freeserve.co.uk> writes:
On most implementations, sizeof ("Hello, world!") - 1 != 13. Usually
the result will be 3 or 7.


Are you sure? A string literal has type array of char (6.4.5#5), and
when it is operand of the sizeof operator, it is /not/ converted to a
pointer type (6.3.2.1#3).

Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #14

On Thu, 27 May 2004, Christian Bau wrote:

On most implementations, sizeof ("Hello, world!") - 1 != 13. Usually the
result will be 3 or 7.


I count three replies so far along the lines of "gee, I think you're
probably wrong." Just for the record: fourteen minus one is thirteen
on every C implementation in existence. It is *never* 3, and it is
*never* 7. Christian's statement was just plain wrong.

-Arthur

Nov 14 '05 #15
"Arthur J. O'Dwyer" wrote:
On Thu, 27 May 2004, Christian Bau wrote:

On most implementations, sizeof ("Hello, world!") - 1 != 13.
Usually the result will be 3 or 7.


I count three replies so far along the lines of "gee, I think
you're probably wrong." Just for the record: fourteen minus
one is thirteen on every C implementation in existence. It is
*never* 3, and it is *never* 7. Christian's statement was
just plain wrong.


I think he is suffering from a temporary delusion that the parens
cause the string to be represented by a pointer. We all have
these problems when a cow flies by.

--
fix (vb.): 1. to paper over, obscure, hide from public view; 2.
to work around, in a way that produces unintended consequences
that are worse than the original problem. Usage: "Windows ME
fixes many of the shortcomings of Windows 98 SE". - Hutchison
Nov 14 '05 #16
On Thu, 27 May 2004 13:51:58 +0100,
Thomas stegen <ts*****@cis.strath.ac.uk> wrote:

sugaray wrote:
hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


#include <stdio.h>
#include <string.h>

int main(void)
{
char s[20] = "hello";
char *ptr = "hello2";

printf("s: sizeof == %u, strlen == %u\n", sizeof s, strlen(s));
printf("ptr: sizeof == %u, strlen == %u\n", sizeof ptr, strlen(ptr));

return 0;
}

Another example

#include <stdio.h>
#include <string.h>

void sub(char s[20])
{
printf("s: sizeof == %u, strlen == %u\n", sizeof s, strlen(s));
}
int main(void)
{
char s[20] = "hello, world";

sub(s);

return 0;
}

Villy
Nov 14 '05 #17
In article <cu*************@zero-based.org>,
Martin Dickopp <ex****************@zero-based.org> wrote:
Christian Bau <ch***********@cbau.freeserve.co.uk> writes:
On most implementations, sizeof ("Hello, world!") - 1 != 13. Usually
the result will be 3 or 7.
Are you sure?


I was sure. I was also wrong.
A string literal has type array of char (6.4.5#5), and
when it is operand of the sizeof operator, it is /not/ converted to a
pointer type (6.3.2.1#3).

Nov 14 '05 #18
"Arthur J. O'Dwyer" wrote:
I count three replies so far along the lines of "gee, I think you're
probably wrong."


I generally try to avoid the Dan Pop "engage your brain" rhetoric. After
all, I'm not perfect and I appreciate when people are relatively gentle
when my imperfections surface.


Brian Rodenborn
Nov 14 '05 #19
On Thu, 27 May 2004 13:51:58 +0100, Thomas stegen
<ts*****@cis.strath.ac.uk> wrote in comp.lang.c:
sugaray wrote:
hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


#include <stdio.h>
#include <string.h>

int main(void)
{
char s[20] = "hello";
char *ptr = "hello2";

printf("s: sizeof == %u, strlen == %u\n", sizeof s, strlen(s));
printf("ptr: sizeof == %u, strlen == %u\n", sizeof ptr, strlen(ptr));


Passing an uncast size_t to printf() to match a conversion specifier
of "%u" is undefined behavior, of course, and just plain doesn't work
on some implementations.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #20
"sugaray" <ru****@sohu.com> wrote:
hi, it just came up my mind that since we can get the length
of any given string literal S with 'sizeof S-1', so, what's
the merit of library function strlen()'s existence ? thanx
in advance for your instruction.


The other replies to your post have covered the case of applying sizeof to
something other than a string literal.

I just thought I would point out that even string literals can give quite
different results between sizeof(S)-1 and strlen(S).

consider when S is "hello \0 world".
sizeof "hello \0 world" - 1 == 13
strlen("hello \0 world") == 6

--
Simon.
Nov 14 '05 #21
On 28 May 2004 07:15:21 GMT, Villy Kruse
<ve*@station02.ohout.pharmapartners.nl> wrote:
On Thu, 27 May 2004 13:51:58 +0100,
Thomas stegen <ts*****@cis.strath.ac.uk> wrote:

sugaray wrote:
hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.


#include <stdio.h>
#include <string.h>

int main(void)
{
char s[20] = "hello";
char *ptr = "hello2";

printf("s: sizeof == %u, strlen == %u\n", sizeof s, strlen(s));
printf("ptr: sizeof == %u, strlen == %u\n", sizeof ptr, strlen(ptr));

return 0;
}

Another example

#include <stdio.h>
#include <string.h>

void sub(char s[20])
{
printf("s: sizeof == %u, strlen == %u\n", sizeof s, strlen(s));
}
int main(void)
{
char s[20] = "hello, world";

sub(s);

return 0;
}


Another example of what? How to write code that invokes undefined
behavior? Or how to confuse the issue to the point where it no longer
relates to the OP's original question?

strlen returns a size_t. sizeof evaluates to a size_t. %u can only
be used for unsigned int. On many systems, size_t is not an unsigned
int.

In spite of appearances, the parameter s in sub is not an array but a
pointer. The OP's question was about string literals of which there
are none in sub.
<<Remove the del for email>>
Nov 14 '05 #22

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
by: Martin Pohlack | last post by:
Hi, I have a funtion which shall compute the amount for a later malloc. In this function I need the sizes of some struct members without having an instance or pointer of the struct. As...
10
by: Trevor | last post by:
If I have a string that should be NULL terminated, is it good practice to use "sizeof(str)" or "sizeof(str) - 1" when using a function like strncpy? If I have a 'string' that should NOT be NULL...
81
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there...
11
by: D | last post by:
hi, i would like to know how to calculate the size of a dynamic array created using a dereference declaration like int *numbers and allocating via malloc or calloc: numbers=(int...
2
by: MarcSmith | last post by:
Code ------------------- void FullPath( char *newp, char *oldp, char *ext) { char *p = strchr( oldp, '.' ); if (p!=NULL) *p='\0'; snprintf( newp, sizeof(newp), "%s%s", oldp, ext ); }
83
by: rahul8143 | last post by:
hello, what is difference between sizeof("abcd") and strlen("abcd")? why both functions gives different output when applied to same string "abcd". I tried following example for that. #include...
2
by: sathishc58 | last post by:
Hi All Please explain why strlen returns() "16" as output here and explain the o/p for sizeof() as well main() { char a={'a','b','c'}; printf("strlen=%d\n", strlen(a));...
31
by: Jean-Marc Bourguet | last post by:
jacob navia <jacob@nospam.comwrites: I'd first align and then use that. You may get a trap with unaligned access even on machine where unaligned access doesn't normally trap if you stump on...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.