为什么我的 for 循环会增加 C 中数组的大小?
我正在尝试用 c 语言制作一个二进制数字计算器,但遇到了 for 循环将第二个数组的大小加倍并将第一个数组添加到末尾的问题。我真的很困惑,因为我认为在声明之后就无法增加大小了。它也发生在我的方程读取函数中,但在这个补函数中,它更容易看到。有关如何解决此问题的任何想法?代码输出
I'm trying to make a binary number calculator in c and I'm running into issues of my for loops doubling the size of my second array and adding the first array onto the end. I'm really confused because I thought you couldn't increase the size after already declaring it. It is happening in my equation reading function as well but in this ones complement function it's a bit simpler to see. Any ideas of how to fix this?the codethe output
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
欢迎来到堆栈溢出。从下次开始,请使用内联代码编辑器来放置代码而不是图像。我已尽力将您的代码放入答案本身来解释问题。请将此视为礼貌。这样做很不寻常。但由于你是新成员,所以我会这样做。
答案:
continue;
。cb3n
数组的最后一个单元格中添加'\0'
。所以 puts() 知道字符串何时结束&停止打印。因此,要快速解决此问题,您可以创建带有额外单元格的数组,并将所有值分配为
'\0'
。所以复制十五个1后,最后会出现'\0'
。我认为在你的情况下,打印的那些额外的零可能是垃圾值。看起来数组加倍了,但事实并非如此,它只是打印超出分配内存的值,因为尚未提供'\0'
。welcome to stack-overflow. From next time please use inline code editor to put your code instead of images. I have taken effort put your code in the answer itself to explain the problem. Please consider this as courtesy. Its very unusual to do it. But as you are a new member, I'm doing it.
Answer:
continue;
in if-else blocks.'\0'
in the last cell ofcb3n
array. soputs()
knows when string ends & stop printing.so to quickly fix this issue you can create array with extra cell and assign all values as
'\0'
. so after copying fifteen 1's there will be'\0'
in the end. I think in your case those extra zeros being printed might be garbage values. It looks like array is doubling but it isn't, its just printing values beyond allocated memory because'\0'
has not been provided.