Possible Duplicate:
C -> sizeof string is always 8
If I do sizeof("HELLO");
I get 6, which is expected, however if I have:
void printLength(char *s) {
sizeof(s);
}
When passing "Hello" to to this function sizeof
returns 8.
Why is this?
Possible Duplicate:
C -> sizeof string is always 8
If I do sizeof("HELLO");
I get 6, which is expected, however if I have:
void printLength(char *s) {
sizeof(s);
}
When passing "Hello" to to this function sizeof
returns 8.
Why is this?
What you are getting is size of char *
. To get it's actual length, use strlen
.
It doesn't change. Arrays aren't pointers. sizeof("HELLO")
gives you the size of the char
array {'H','E','L','L','O','\0'}
, and the sizeof(s)
gives you the size of a pointer.
Because string literals and arrays declared to be of a fixed size are treated specially. The compiler knows exactly how big they are.
In your function, all the compiler knows is that it's a pointer to something. You are taking the size of the character pointer (which at that point, is all the compiler knows about it). You're on a 64 bit system, so you get an 8 byte pointer, no matter what you feed into the function.
There is a library function to do this for you:
#include <string.h>
int getLength(char * str)
{
return strlen(str);
}