I defined an array:
char arr[1480];
Now, from a file, I read exactly 1480 chars and put into arr (by doing arr[i]=c).
I know 1480 chars because I use a while loop to read one char ar a time (istream.get()) and stop when the incrementing index = 1480.
However, after that, I do strlen(array) and it returns 1512. How come? This only happens in some occasions, but not in all occasions, even though every time I read from file, I always read up to 1480 chars.
My doubt is one char might occupy more than 1 unit (units returned by strlen(arr)).
If so, how can I fix this?
Thanks
PS: I asked a problem earlier about my pointer gets garbaged, and this is the cause when I have a buffer (arr) of length > 1480.
解决方案
The array size must include the string terminator. Since you read exactly the size of the array then you can't (and don't) add the string terminator. The strlen function, and all other string functions, uses the string terminator character to find the end of the string. If it's not there it will continue until it finds it.
If you may have no more than 1480 characters in the string, you should have an array of size 1481, with the last being the string terminator '\0'.