打印出以垃圾结尾的整数数组
我有以下代码,应该打印 3072 个整数的数组:
for(int q=0; q < 3072; q++) printf("%x", band->GetData(q));
人们会假设它将打印 3072 个整数,但是我得到 3075 个整数,最后有 3 个可能是垃圾整数。使用此代码
打印到文件的
fp=fopen("filename", "w");
fwrite(band->GetBuffer(), sizeof(int), 3072, fp);
fclose(fp);
结果几乎相同,只是末尾有 3 个额外字节。使用不同的数组会产生不同长度的垃圾。
我想问一下为什么会出现这种情况,是否真的是垃圾。
谢谢。
int GetData(unsigned int pos) const { ASSERT(pos < m_size); return m_data[pos]; }
int* GetBuffer() { return m_data; }
I have following code which should print array of 3072 integers:
for(int q=0; q < 3072; q++) printf("%x", band->GetData(q));
one would assume that it will print 3072 integers, however I get 3075 integers with 3 probably garbage ones at the end. Printing to the file using this code
fp=fopen("filename", "w");
fwrite(band->GetBuffer(), sizeof(int), 3072, fp);
fclose(fp);
ends almost the same, except there are 3 extra bytes at the end. Use of different arrays gives different length of garbage.
I would like to ask why that happens and whether it is really a garbage.
Thank you.
int GetData(unsigned int pos) const { ASSERT(pos < m_size); return m_data[pos]; }
int* GetBuffer() { return m_data; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
fwrite
的问题可能是因为您以文本模式打开文件,写入文件的任何0x0a
字节都将扩展为0x0d 0x0a< /代码>。
printf 的问题是您没有在数字之间放置任何分隔符,因此您错误地计算了输出。
The problem with the
fwrite
is probably because you've opened the file in text mode, and any0x0a
bytes written to the file will be expanded to0x0d 0x0a
.The problem with the
printf
is that you're not putting out any separators between the numbers, so you're miscounting the output.