char数组的strlen大于其大小.如何避免?

编程入门 行业动态 更新时间:2024-10-24 18:16:18
本文介绍了char数组的strlen大于其大小.如何避免?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我定义了一个数组:

char arr [1480];

char arr[1480];

现在,从文件中,我准确地读取了1480个字符并将其放入arr(通过执行arr [i] = c). 我知道1480个字符,因为我使用while循环一次读取一个字符(istream.get()),并在递增索引= 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.

但是,在那之后,我执行strlen(array)并返回1512.为什么呢?这只会在某些情况下发生,但并非在所有情况下都发生,即使每次我从文件中读取数据时,我总是会读取多达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.

我怀疑一个char可能占用超过1个单位(由strlen(arr)返回的单位). 如果是这样,我该如何解决?

My doubt is one char might occupy more than 1 unit (units returned by strlen(arr)). If so, how can I fix this?

谢谢

PS:我之前曾问过一个有关我的指针被浪费的问题,这就是当我有一个长度大于1480的缓冲区(arr)时的原因.

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.

推荐答案

数组大小必须包含字符串终止符.由于您精确地读取了数组的大小,因此您不能(也不能)添加字符串终止符. strlen函数以及所有其他字符串函数,使用字符串终止符查找字符串的结尾.如果不存在,它将继续直到找到它.

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.

如果字符串中的字符数不能超过1480个,则应具有大小为1481的数组,最后一个是字符串终止符'\0'.

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

更多推荐

char数组的strlen大于其大小.如何避免?

本文发布于:2023-07-29 00:49:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235711.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   于其   大小   char   strlen

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!