0

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?

Community
  • 1
  • 1
Mark Provan
  • 1,041
  • 2
  • 13
  • 19

3 Answers3

6

What you are getting is size of char *. To get it's actual length, use strlen.

Mahesh
  • 34,573
  • 20
  • 89
  • 115
4

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.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
3

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);
}
Wug
  • 12,956
  • 4
  • 34
  • 54