strlen of a char array is greater than its size. How to avoid?

落花浮王杯 提交于 2019-12-12 02:59:59

问题


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.


回答1:


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'.




回答2:


Try to write in this way ? Just a little sample

char arr[1481]=0x00; //define all the array with string terminator
memcpy(arr,BufCopyFrom, 1480); //BufCopyFrom is the Buffer being copied and specified to copy 1480 bytes.

Hope it helps.



来源:https://stackoverflow.com/questions/16381307/strlen-of-a-char-array-is-greater-than-its-size-how-to-avoid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!