implicit cast of pointer loses '__packed' qualifier

> I have a packet structure which has a field of Integer arrays, that is
>
> packed struct
> {
> int a;
> char b;
> int count[100];
> }foo;
>
> I need to initialize all the entries of count to a particular value,
> how do I do it?
>
> struct foo *temp= (struct foo*)malloc(sizeof(struct foo));
> memset(temp->count,0,sizeof(temp->count))
>
> Gives compiler error
> Error: C2906E: <argument 1 to 'memset'>: implicit cast of pointer loses
> '__packed' qualifier

Don't cast the result of malloc(); it's unnecessary and can mask
errors such as failing to include <stdlib.h> or using a C++ compiler
to compile C code. The recommended form for your malloc() call is:

struct foo *temp = malloc(sizeof *tmp);

Note that you only have to specify the type in one place, which could
avoid errors if you ever change the type.

But your real problem is the "packed" (or "__packed") qualifier.
There is no such qualifier in standard C; it appears to be an
implementation-specific extension. The fact that the error message
refers to "__packed" rather than "packed" probably indicates that
you've included a header that has something like:

#define packed __packed

(The identifier "__packed" can legally be used as an
implementation-specific keyword; "packed" cannot, unless you use an
implementation-specific header.)

Since the message complains about an "implicit cast" (more on that in
a moment), it's likely that an explicit cast would avoid the error
message:

memset( (void*)temp->count,0,sizeof temp->count);

*But* keep in mind that this cast is simply a way of telling the
compiler, "Shut up, I know what I'm doing". Before you try this make
sure you really do know what you're doing. We have no way of knowing
exactly what "packed" means, so we can't guess whether the cast will
cause problems. Consult your compiler's documentation.

Using memset() to zero an array of int is ok, but subtly so. It's
guaranteed that all-bits-zero is a valid representation for value 0 in
any integer type. The standard doesn't actually say so, but the
committee has made a ruling in response to defect report; I'm
reasonably sure this is ok in all existing implementations, so you can
safely count on it.

Finally, there is no such thing as an "implicit cast". The error
message should refer to an "implicit conversion". A cast is an
operator that performs a conversion; it can't be implicit.
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值