简体   繁体   English

如何使用 C 中的指针访问结构成员?

[英]How do I access a structure member with a pointer in C?

I am practicing with linklist in C .我正在练习C中的链接列表。 My objective is that I want to delete a node using a function outside of main.我的目标是我想在 main 之外使用 function 删除一个节点。
My plan to accomplish this objective is to access the next pointer without clearing/deleting/freeing the head pointer, but I get an error:我实现这个目标的计划是在不清除/删除/释放头指针的情况下访问下一个指针,但我收到一个错误:

"[Error] request for member 'nextptr' in something not a structure or union" “[错误] 在非结构或联合的情况下请求成员 'nextptr'”

The code:编码:

void del(struct node **head) {
    struct node *temp = *head;
    //this is what I believe is wrong, i need to access nextptr of head
    *head->nextptr = temp->nextptr->nextptr;
    free(temp->nextptr);
    temp->nextptr = NULL;

Postfix operators like -> have higher precedence than unary * , so *head->nextptr is parsed as *(head->nextptr) - you're trying to apply the -> operator to head (not *head ), which is a pointer to a pointer to a struct type, hence the error.->这样的后缀运算符比一元*具有更高的优先级,因此*head->nextptr被解析为*(head->nextptr) - 您正在尝试将->运算符应用于head (不是*head ),这是指向struct类型指针的指针,因此出现错误。

To fix it, you need to explicitly dereference head before applying the -> operator, so you need to write it as (*head)->nextptr .要修复它,您需要在应用->运算符之前显式取消引用head ,因此您需要将其写为(*head)->nextptr

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

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