点运算符和箭头运算符之间的差异,用于c或c ++中树创建的结构对象变量

时间:2014-02-20 21:23:44

标签: c++ c

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

假设我有这样的结构:

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

typedef struct Huffman Node;
Node * tree;

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

Arrorw运营商:

 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)如何在内存中分配它们?

3 个答案:

答案 0 :(得分:4)

(1):->只是(*).的快捷方式,例如:

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

答案 1 :(得分:1)

如果有指向结构实例的指针,则使用箭头操作符:->

如果您有结构的变量或直接实例,则使用点运算符.

在这些情况下,将以相同的方式访问类,为成员提供正确的可访问性。

答案 2 :(得分:1)

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

表达式tree具有类型“指向struct Huffman的指针”,因此您使用->运算符来访问成员。

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

基本上,a->b(*a).b更具可读性。