Sizeof vs. Strlen

R

Ralmin

sugaray said:
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
 
B

Barry Schwarz

sugaray said:
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>>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top