关于取消引用"void *"指针 [英] Regarding dereferencing 'void *' pointer

查看:315
本文介绍了关于取消引用"void *"指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到如何从下面的代码行中删除上述警告. data是空指针,作为回调函数的一部分,它将在数据指针中接收字符串.由于我已经强制转换了void指针,但是编译器仍然显示警告.

I am not able to find out how to remove the above warning from the below line of code. data is is void pointer and as part of callback function will be receiving string in the data pointer. As I have typecast the void pointer but compiler still showing the warning.

下面一行基本上显示了两个警告. 1.取消引用"void *"指针 2.接受类型为'void

There are basically two warnings showing up on the below line. 1. dereferencing 'void *' pointer 2. taking address of expression of type 'void

 service_ind = atoi((const char*)&data[at_response.param[0].start_of_value_index]) ? TRUE:FALSE ;

以下是必填信息

void * data;
AT_PARSER_RESPONSE at_response;

typedef struct
{

/*Other parameters */

AT_PARAM  param[AT_MAX_NUM_PARAM];

}AT_PARSER_RESPONSE

推荐答案

引用C11,第6.5.3.2章:

Quoting C11, chapter §6.5.3.2:

一元*运算符表示间接.如果操作数指向一个函数,则结果为 功能指示符;如果它指向一个对象,则结果是一个左值,表示 目的.如果操作数的类型为要输入的指针",则结果的类型为类型". 如果 无效的值已分配给指针,一元*运算符的行为是 未定义.

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

因此,您的代码会导致未定义的行为.

So, your code causes undefined behavior.

与此相关的是第6.2.5章中的内容:

Also, related, from chapter §6.2.5:

void类型包含一组空值; 这是一种不完整的对象类型, 无法完成.

The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

因此,指向void 的指针是用于取消引用的无效操作数.

So, a pointer to void is an invalid operand for dereference.

一个可能的实际案例和可能的解决方案

有时,为了制作泛型,我们将某个指针投射到void *,将其作为参数传递给函数,然后在函数内部,根据一些已知信息将其投射回原始类型.根据第6.3.2.3节,这是完全有效的:

Sometimes, for making generics, we cast a certain pointer to void *, pass that as argument to a function and then, inside a function we cast it back to the original type, based on some known information. This is, as per chapter §6.3.2.3, perfectly valid:

[...]指向的指针 任何对象类型都可以转换为指向void的指针并再次返回;结果应 比较等于原始指针.

[...] A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

如果是这种情况,并且要在函数内部取消引用,则可以将指针强制转换为任意一个

If this is your case, and you're dereferencing inside the function, you can cast the pointer to either

取消引用之前.

这篇关于关于取消引用"void *"指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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