简体   繁体   English

转换void指针(在struct中工作时)

[英]Casting void pointer (while working in struct)

Im very new (few weeks) to the whole C programming so please take it easy on me ;-) 我对整个C编程非常新(几周),所以请放轻松我;-)

Project details: I'm currently working on making a train travelplanner system, using a given trainplan to find the shortest route to a specific destination. 项目详情:我目前正致力于制定火车旅行计划系统,使用特定的火车计划找到到达特定目的地的最短路线。 This is done making a graph, a binary heap for sorting, and then the dijkstra algortihm. 这样就完成了图形,二元堆的排序,然后是dijkstra algortihm。 Hence the sorta messy structs (sorry! figured it was the best to get familiar with them). 因此,混乱的结构(抱歉!认为最好熟悉它们)。

My issue: I built a linkedlist, having data as void inside a struct (making it more general purpose for reuse), however when I want to cast the data while working with structs, I get a syntax error. 我的问题:我构建了一个链表,在结构中将数据作为void(使其更通用于重用),但是当我想在使用结构时转换数据时,我得到语法错误。

The struct: 结构:

typedef struct  linked_list{
    void *data;
    struct linked_list *next;
    struct linked_list *previous;
} linked_list;

And my, probably, glaring error: 我可能会发出明显的错误:

if(current->((edge*)data)->to->distance > ...

This works perfectly fine if I change the data type to being edge in my struct (and not trying this stunt), but casting in this case apparently does not work. 如果我将数据类型更改为我的结构中的边缘(而不是尝试此特技),这完全正常,但在这种情况下,转换显然不起作用。

If more details are needed, please let me know. 如果需要更多详细信息,请告知我们。

((edge*)current->data)->to->distance

The right operand of the -> operator must be the name of a member of a struct (or union); ->运算符的右操作数必须是结构(或联合)成员的名称; it cannot be a cast expression. 它不能是演员表达。

current is an expression of type linked_list (presumably). currentlinked_list类型的linked_list (推测)。

current->data is an expression of type void* . current->datavoid*类型的表达式。

To convert that void* expression to an edge* expression, you need to apply a cast to the expression, not to the member name, so: 要将void*表达式转换为edge*表达式,您需要将强制转换应用于表达式,而不是成员名称,因此:

(edge*)current->data is an expression of type edge* (edge*)current->dataedge*的表达式

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

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