在C ++中分配unsigned char数组的问题 [英] Problem allocating an unsigned char array in C++

查看:237
本文介绍了在C ++中分配unsigned char数组的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从BMP文件中读取字节,并将它们分配到unsigned char数组中,以将其用作Open GL应用程序中的纹理。



到目前为止,这就是我定义数组的方式:



  unsigned   char  * data =  new   unsigned   char  [imageSize]; 





是imageSize一个unsigned int,它定义了位图,以字节为单位。



问题是,当我运行应用程序时,数据的长度为4个字节,而不是imageSize的值。我做了一个日志来跟踪程序的作用,这就是它给我的东西:



日志:imageSize:786434 

日志:图片宽度:512

日期:图片高度:512

错误:无法分配数据缓冲区(字节):4

错误:缓冲区所需的字节数:786434





换句话说,数据应该是786434字节长的数组。相反,我得到一个4字节长的数组。



我也尝试过很多东西,比如



< pre lang =c ++> unsigned char * data;
data = new unsigned char [imageSize];





还将其定义为



 data =( unsigned   char  *)malloc(imageSize); 





但是他们都没有因某些原因而工作。即使我手动分配它的长度,它也行不通。



我在Visual Studio 2010中编程,对于Windows,它是32位application。

解决方案

不,4个字节是指向数据的指针的大小,实际数据的大小为 imageSize 。您正确地在堆上分配了数组。 (最好不要在C ++中使用 malloc ,使用 new 。)问题出在传递此方法的方法中数据。在这种情况下不要查看日志,请查看名为调用堆栈的调试窗口。



怎么办? 1)了解您使用此数据的API,只需阅读文档。 2)正确学习C ++指针和数组,不要盲目折叠。



-SA

I want to read the bytes from a BMP file, and allocate them into an unsigned char array to use it as a texture in an Open GL application.

So far, this is how I define my array:

unsigned char* data = new unsigned char [imageSize];



being imageSize an unsigned int that defines the size of the bitmap, in bytes.

The problem is that when I run the application, data has a length of 4 bytes, instead of the value of imageSize. I made a log to track what the program does, and this is what it gives to me:

LOG: imageSize : 786434

LOG: image width : 512

LOG: image height : 512

ERROR: Failed to allocate Data Buffer (bytes) : 4

ERROR: Required bytes for the buffer : 786434



In other words, data should be a 786434 bytes long array. Instead, I get a 4 bytes long array.

I also tried doing many things like

unsigned char* data;
data = new unsigned char [imageSize];



Also defining it as

data = (unsigned char*)malloc(imageSize);



But none of them work for some reason. Even if I assign to it the length manually, it won't work.

I'm programming this in Visual Studio 2010, for Windows, and it's a 32 bit application.

解决方案

No, 4 bytes is the size of the pointer to data, and actual data has the size of imageSize. You allocated the array on the heap correctly. (Better don't use malloc with C++, use new.) The problem is in the method where you pass this data. Don't look at the log in this case, look at the debug window called "Call stack".

What to do? 1) Learn the API you are using with this data, just read the documentation. 2) Learn C++ pointers and arrays properly, don't be so blind-folded.

—SA


这篇关于在C ++中分配unsigned char数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆