【问题标题】:Basic C pointer syntax [closed]基本 C 指针语法 [关闭]
【发布时间】:2016-04-24 00:45:00
【问题描述】:

据我所知, * 符号通常出现在基本类型的变量之前(例如 int )。但是,我遇到了如下一行代码:

insert(int key, struct node **leaf)
{
    if( *leaf == 0 )
        {
        *leaf = (struct node*) malloc( sizeof( struct node ) );
        (*leaf)->key_value = key;
        /* initialize the children to null */
        (*leaf)->left = 0;    
        (*leaf)->right = 0;  
    }
    else if(key < (*leaf)->key_value)
    {
        insert( key, &(*leaf)->left );
    }
    else if(key > (*leaf)->key_value)
    {
        insert( key, &(*leaf)->right );
    }
}

当 * 符号出现在结构之前(例如 struct node*)时,它是如何工作的?

谢谢。

【问题讨论】:

  • 我最近在这段代码中看到了 * 符号:return 3 * 5;。我真的很想知道 是如何工作的;据我所知,5 不是指针。
  • 也许阅读任何关于 c 的书,而不是等待某人输入类似但不那么深入的内容
  • 我一直在互联网上寻找答案(现在买不起教科书)。对于否则浪费您的时间,我深表歉意。
  • 我留下了一个关于这里到底发生了什么的答案,但你需要学习和理解 C 指针的基础知识(声明、分配、运算符 & 的地址、取消引用运算符 * 等...)
  • 你没有图书馆吗?或者大学里的二手书店

标签: c pointers syntax


【解决方案1】:

leaf 作为指向指针的指针。这意味着它指向内存中的指针。 并且* 运算符取消引用其操作数。所以*leaf 表示leaf 指向的指针的值。实际上,正如我所见,这个结构与树数据结构有关。此代码实际上为leaf 指向的位置(内存中的一个位置)分配内存:

*leaf = (struct node*) malloc( sizeof( struct node ) );

struct node 是用户定义的类型,struct nod * 表示指向struct node 类型变量的指针的类型。

【讨论】:

  • "leaf 作为指针的指针。"你是怎么知道这个的?从显示的代码中只是一个指针,指向任何东西的指针,OP 不会告诉它指向哪个类型。
  • 它将leaf指向struct node * 的值转换为leafstruct node **
  • 这只是你的假设,一个理智的假设,是的
  • 因为我们没有看到相关的代码。这可能是这个问题收到如此多反对票的原因。
  • 是的,但从源头上他看到的很可能是struct node **
【解决方案2】:

* 在 C 中既是二元运算符又是一元运算符,它在不同的上下文中表示不同的含义。

根据您提供的代码:

*leaf = (struct node*) malloc( sizeof( struct node ) );

这里malloc 返回的void *(空指针)被转换为指向struct node 的指针,我不建议这样做,更多信息请阅读this

我猜如果你看到leaf的声明会是这样的:

struct node ** leaf; //declares a pointer to a pointer of struct node

leaf = malloc(sizeof(struct node *) ); //allocate enough memory for pointer
//remember to not cast malloc in C

此时*leaf 是指向struct node 的指针,其中* 充当解引用运算符。

【讨论】:

  • 感谢您的详细回答。我没有将其视为类型转换,但很明显现在是。为非常有用的解释干杯!
猜你喜欢
  • 2012-07-21
  • 1970-01-01
  • 2018-08-26
  • 2018-10-30
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
相关资源
最近更新 更多