C language, how find the length of a word in a 2d array?

Alex picture Alex · Apr 4, 2013 · Viewed 12.7k times · Source

I am trying to make a condition for a for loop where i have to say (c<wordlength) but im not sure how to find the length of the word.

so lets say i have an arrary called...

char shopping[10][10]={"BAGELS","HAM","EGGS"};

what is the right syntax to find that shopping[0] has 6 letters?

Answer

NPE picture NPE · Apr 4, 2013

The right syntax is

strlen(shopping[0])

This returns a value of type size_t that does not include the NUL terminator.

See man strlen for details.

If you are using strlen(unchanging_string) as the terminal condition of a loop, it is prudent to call it once before the loop instead of calling it on every iteration.

An alternative way to loop over the characters of shopping[0] is as follows:

char *s = shopping[0];
while (*s) {
  /* (*s) is the current character */
}