gpt4 book ai didi

c - 关于取消引用 'void *' 指针

转载 作者:太空狗 更新时间:2023-10-29 16:05:42 24 4
gpt4 key购买 nike

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

下面一行基本上显示了两个警告。1.取消引用'void *'指针2. 获取类型为'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:

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.

因此,您的代码会导致 undefined behavior .

此外,相关的,来自第 6.2.5 章:

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

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


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

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

[...] 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.

如果这是你的情况,并且你在函数内部取消引用,你可以将指针转换为任何一个

在取消引用之前。

关于c - 关于取消引用 'void *' 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44328870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com