Actually shopping[0]
has 7 chars one you forgot \0
char that is for string termination. Although strlen()
give you length of string, that number of char before \0
.
strlen(shopping[0])
But Total char are strlen(shopping[0]) + 1
= 7
In memory your shopping[0]
is something like:
+----+----+----+---+---+----+----+----+---+---+
| 'B'| 'A' |'G'|'E'|'L'| 'S'|'\0'| 0 | 0 | |
+----+----+----+---+---+----+----+----+---+---+
^ `\0` also a char in shopping[0]
Edit:
As I read your question again you says 6 letters So strlen(shopping[0]
)
is your answer give you 6.
Because you wants a loop to find number of letters (char in my answer non '\0') then calling strlen()
is useless. I would like that you should take benefit of null termination string in C:
int num=0;
for(num = 0; shopping[0][num]!='\0'; num++);
printf("\n number of letters are %d\n",num);
I think other answers are not good, they are using strlen() unnecessary. If I am missing something, Please let me know