user2393426
user2393426

Reputation: 165

Get length of item in multiple dimension array C

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?

Upvotes: 0

Views: 79

Answers (1)

Bathsheba
Bathsheba

Reputation: 234655

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.

Upvotes: 3

Related Questions