Reputation: 13
#include <stdio.h>
int main()
{
char * name = "bob";
int x = sizeof(name);
printf("%s is %d characters\n",name,x);
}
I have the above code. I want to print the number of characters in this string. It keeps printing 8
instead of 3
. Why?
Upvotes: 1
Views: 50
Reputation:
sizeof()
returns byte size. Specifically, it gives the bytes required to store an object of the type of the operand. In this case sizeof()
is returning the byte size of a pointer to a string, which on your computer is 8 bytes, or, 64-bits.
strlen()
is what you are looking for:
#include <stdio.h>
#include <string.h> // include string.h header to use strlen()
int main()
{
char * name = "bob";
int x = strlen(name); // use strlen() here
printf("%s is %d characters\n",name,x);
}
Upvotes: 2
Reputation: 123458
strlen
gives you the number of characters in a string. sizeof
gives you the size of the object in bytes. On your system, an object of type char *
is apparently 8 bytes wide.
Upvotes: 0
Reputation: 25705
use strlen
for finding the length of a string.
Each character is atleast 1 byte wide. It prints 8
because sizeof
gets a pointer to bob
and, on your machine, a pointer is 8
bytes wide.
Upvotes: 1