gpt4 book ai didi

c - 在c中使用*代替->运算符

转载 作者:行者123 更新时间:2023-11-30 18:16:20 25 4
gpt4 key购买 nike

我用 C 语言创建了一个非常简单的链表程序。

#include<stdio.h>
#include<stdlib.h>

int main(){
struct Int{
int num;
struct Int *ptr;
};
typedef struct Int NODE;
NODE *start;
start = (NODE *) malloc(sizeof(NODE));
(*start).num = 100;
(*start).ptr = (NODE *) malloc(sizeof(NODE));

(*start).(*ptr).num = 123;
(*start).(*ptr).ptr = NULL;

}

当我将最后两行替换为:-

start -> ptr -> num = 123;
start -> ptr -> ptr = NULL;

错误已解决。

问题是为什么我不能使用 (* start). 而不是 start -> 。根据这个答案 What does this mean "->"? 两者是相同的。

最佳答案

你应该将最后两行写成:

(*(*start).ptr).num = 123;
(*(*start).ptr).ptr = NULL;

因为 (*ptr) 不是 (*start) 的成员,因此您应该访问 ptr,然后取消引用整个表达式。

关于c - 在c中使用*代替->运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37628038/

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