Find the size of a string pointed by a pointer

The strlen() function provided by string.h gives you how many "real characters" the string pointed by the argument contains. However, this length does not include the terminating null character '\0'; you have to consider it if you need the length to allocate memory.

That 4 bytes is the size of a pointer to char on your platform.


Use strlen to find the length of (number of characters in) a string

const char *ptr = "stackoverflow";
size_t length = strlen(ptr);

Another minor point, note that ptr is a string literal (a pointer to const memory which cannot be modified). Its better practice to declare it as const to show this.


  1. sizeof() returns the size required by the type. Since the type you pass to sizeof in this case is a pointer, it will return size of the pointer.

    If you need the size of the data pointed by a pointer you will have to remember it by storing it explicitly.

  2. sizeof() works at compile time. so, sizeof(ptr) will return 4 or 8 bytes typically. Instead use strlen.

Tags:

C