【问题标题】:difference between the dot operator and arrow operator by structure object variable for tree creation in c or c++ [duplicate]在c或c ++中通过结构对象变量创建树的点运算符和箭头运算符之间的区别[重复]
【发布时间】:2014-03-22 02:39:29
【问题描述】:

我必须澄清一个疑问,它在 c 和 c++ 中也具有相同的概念。

假设我有一个这样的结构:

struct Huffman
{
    int value;
    unsigned char sym;                 /* symbol */
    struct Huffman *left,*right;    /* left and right subtrees */
};

typedef struct Huffman Node;
Node * tree;

现在我使用树变量创建树。然后同时使用点运算符和箭头运算符。 像这样。

箭头运算符:

 for (i = 0; i < data_size; i++) 
    {
         // the problem is here this tree pointer don't store the values for all alphabets, it just remembers the last executed alphabet after this for loop.
        tree -> left = NULL;
        tree  ->right = NULL;
        tree -> symbol = storesym[i];
        tree  -> freq = storefreq[i];
        tree -> flag = 0;
        tree -> next = i + 1;
        cout<<"check1 : "<<tree -> symbol<<endl;
    } 

点运算符:

for (i = 0; i < data_size; i++) 
{
    tree[i].symbol = storesym[i];
    tree[i].freq = storefreq[i];
    tree[i].flag = 0;
    tree[i].left = tree[i].right = tree[i].value = NULL;
    tree[i].next = i + 1;
}

现在我无法理解 (1) 两者有什么区别? (2) 它们在内存中是如何分配的?

【问题讨论】:

  • @JosephMansfield 我刚刚编辑过,那是错误的。实际上是树

标签: c++ c


【解决方案1】:

. 运算符期望其操作数是 struct ...union ... 类型的表达式。 -&gt; 运算符期望其操作数是“指向struct ...”或“指向union ...”的指针类型的表达式。

表达式tree 的类型为“指向struct Huffman 的指针”,因此您可以使用-&gt; 运算符来访问成员。

表达式tree[i] 的类型为“struct Huffman”;下标运算符隐式取消引用指针(请记住,a[i] 被评估为 *(a + i)),因此您使用 . 运算符来访问成员。

基本上,a-&gt;b 是更易读的(*a).b 等价物。

【讨论】:

  • 你非常接近我想知道的。实际上问题的根源是我在此链接上提出的问题仍未得到解答,请你帮我,实际上我正在创建一棵树(首先使用点运算符然后使用 -> ,所以我成功完成了点运算符但我无法为 -> 运算符做等效操作,这是链接)stackoverflow.com/questions/21910872/…
  • 我也无法理解 a[i]= *(a+i) 的原理,请您解释一下。
  • @user234839:数组访问是根据指针算法定义的;当您编写a[i] 时,编译器将该表达式计算为*(a + i);从a 指定的地址(可以是数组或指针表达式)开始,它计算a 后面的第i' 个元素的地址并取消引用结果。
【解决方案2】:

当您有一个指向结构实例的指针时,您可以使用箭头运算符:-&gt;

当你有一个结构的变量或直接实例时,你使用点运算符,.

在这些情况下,如果成员具有正确的可访问性,则可以以相同的方式访问类。

【讨论】:

    【解决方案3】:

    (1):-&gt; 只是(*). 的快捷方式例如:

    string s = "abc";
    string *p_s = &s;
    s.length();
    (*p_s).length(); 
    p_s->length(); //shortcut
    

    【讨论】:

    • 我感谢您的帮助,但我尝试在此链接 stackoverflow.com/questions/21910872/...接线员,你能帮我看看我给你的链接吗?其实这个问题让我问了这个点运算符和箭头运算符的问题
    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 2016-04-14
    • 2010-12-30
    • 2010-11-08
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多