4

I have these defined in the interface of an ObjC class:

unsigned m_howMany;
unsigned char * m_howManyEach;
...

Then later in the code I have this:

 m_howManyEach = malloc(sizeof(unsigned) * m_howMany);

which is where I get a warning "Result of malloc is converted to a pointer of type unsigned char, which is incompatible with sizeof operand type unsigned int"

Could someone please explain the proper use of malloc() in this situation, and how to go about getting rid of the warning?

4

3 回答 3

4

here's your problem:

sizeof(unsigned)

the compiler interprets "unsigned" as "unsigned int", you should specify "unsigned char" like this:

m_howManyEach = malloc(sizeof(unsigned char) * m_howMany);
于 2012-08-28T17:31:00.470 回答
4

First, unsigned is really unsigned int.

The compiler is being nice to you, telling you that you are allocating N items of unsigned, which is not unsigned char.

Also, your later access will be wrong as well.

Change

unsigned char * m_howManyEach;

to

unsigned * m_howManyEach;

because it looks like you really want unsigned int as your type instead of unsigtned char.

Of course, this assumes you really want unsigned integers, and not 1-byte unsigned chars.

If the actual size of your integral values is important, you should consider the sized valued (uint8_t, uint16_t, uint32_t, uint64_t).

于 2012-08-28T17:32:35.237 回答
2

It's weird you are sizing your array based on unsigned int size instead of unsigned char one.

m_howManyEach = malloc(sizeof(unsigned char) * m_howMany);
于 2012-08-28T17:32:11.323 回答