简体   繁体   English

如何强制使用void *结构成员?

[英]How to cast void* struct members?

I'm trying to cast a void* from a struct member. 我正在尝试从结构成员投射void* The struct looks like this: 该结构如下所示:

typedef struct{
    int n;
    void* string;
}query;

And I want to cast the member string to char* and store another string -- lets say str2 --, like this: 我想将成员stringchar*并存储另一个字符串-假设str2像这样:

char* str2 = "hello";
(*(char*)q.string) = str2;

But it keeps telling me this warning: 但是它不断告诉我这个警告:

example.c: In function 'main': example.c:23:33: warning: assignment makes integer from pointer without a cast [-Wint-conversion] (* (char* )q.string) = str2; example.c:在函数'main'中:example.c:23:33:警告:赋值使指针从整数开始,而没有强制转换[-Wint-conversion](*(char *)q.string)= str2;

Why is this isn't working? 为什么这不起作用?

You don't need a cast, at all. 您根本不需要演员表。

That said, in your example, query is a type, not a variable. 就是说,在您的示例中, query是一种类型,而不是变量。

Use it like 像这样使用

query q;
q.string = str2;

A working example 一个有效的例子

The warning is correct. 警告是正确的。 Newer versions of gcc have a more helpful message: 较新版本的gcc具有更有用的信息:

warning: assignment to 'char' from 'char *' makes integer from pointer without a cast [-Wint-conversion] 警告:从'char *'分配给'char'会使指针变为整数,而不进行强制转换[-Wint-conversion]

 13 | (*(char*)q.string) = str2; | ^ 

You dereference a char * which gives you a char . 取消引用char *这给你一个char To that char type you assign str2 which is of type char * . 给该char类型分配str2 ,它的类型为char *

As Sourav Ghosh showed you, you can just do this: 正如Sourav Ghosh向您展示的那样,您可以执行以下操作:

q.string = str2;

If you really want to make the cast explicit: 如果您真的想使演员表明确:

q.string = (void*)str2;

As you see you were doing the cast on the wrong side. 如您所见,您在错误的一侧进行了投射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM