Re: going through each element of a char array in c
Posted 15 March 2011 - 10:00 PM
I hope you don't just memorize "use strlen". Think about what strlen actually does.
Strlen walks through the array, counting until it hits a '\0', and then returns the count. So here are the things to think about:
- If the array does not contain a C string, you have no guarantee that strlen will stop at the array bound (because there's no guarantee of a '\0'). Consequently, you can index out of the array and that's undefined behavior.
- If you are looking to get the size of the array, you can't do that with strlen. That's because it only counts up to the first occurence of '\0'. Unless you happen to have a array that's exactly sized to a contained C string, it's not going to give you the array size.
- And if you really wanted strlen, using it to derive the upper limit in a for loop isn't necessarily sensible. You walk through the array once to get the length, and then you walk through it again. Talk about inefficiency.