0

I construct an array with:

char *state[] = {"California", "Oregon", "Texas"};

I want to get the length of California which should be 10 but when I do sizeof(state[0]), it just gives me 8 ( I think this means 8 bytes since the size of a char is 1 byte). But why 8 though instead of 10? I'm still able to print out each chars of California by looping through state[0][i].

I'm new to C, can someone please explain this to me?

user2393426
  • 165
  • 1
  • 10
  • Use [`strlen`](http://en.cppreference.com/w/c/string/byte/strlen). – juanchopanza Sep 29 '14 at 07:06
  • Use `strlen`, not `sizeof`. – Paul R Sep 29 '14 at 07:06
  • `state[0]` is not a string, it's a char pointer. `sizeof` gives the size of variable in memory, in this case 8 bytes (if state[0] was an integer, it would return 4). C has no concept of string length and the only way to find it out is to iterate through the array until you encounter character `\0` (all strings in C generally end with this character) – makhan Sep 29 '14 at 07:19
  • Check it out what is pointer size in your system.There is chance for 8 is pointer size. – Anbu.Sankar Sep 29 '14 at 07:20

1 Answers1

3

The simplest explanation is that sizeof is a compile-time evaluated expression. Therefore it knows nothing about the length of a string which is essentially something that needs to be evaluated at run-time.

To get the length of a string, use strlen. That returns the length of a string not including the implicit null-terminator that tells the C runtime where the end of the string is.

One other thing, it's a good habit to get into using const char* [] when setting up a string array. This reinforces the fact that it's undefined behaviour to modify any of the array contents.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • These are string literals however, which the sizeof operator does know about. `sizeof("California")` is perfectly fine code and will give the string length. The problem is that the strings are referenced through pointers, so the type information is lost along the way. http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c – Lundin Sep 29 '14 at 08:09