问题描述
我必须澄清一个疑问,即在c和c ++中也具有相同的概念.
I have to clear one doubt which has same concept in c and c++ as well.
假设我有一个这样的结构:
Suppose i have a struct like this:
struct Huffman
{
int value;
unsigned char sym; /* symbol */
struct Huffman *left,*right; /* left and right subtrees */
};
typedef struct Huffman Node;
Node * tree;
现在我使用树变量创建树.然后同时使用点运算符和箭头运算符.像这样.
and now i create tree using tree variable. Then using dot operator and arrow operator both.like this.
Arrorw运算符:
Arrorw operator:
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)如何在内存中分配它们?
推荐答案
.
运算符期望其操作数是 struct ...
或联盟...
.->
运算符期望其操作数是指向 struct ...
的指针"或指向 union ...
".
The .
operator expects its operand to be an expression of type struct ...
or union ...
. The ->
operator expects its operand to be an expression of type "pointer to struct ...
" or "pointer to union ...
".
表达式 tree
的类型为指向 struct Huffman
的指针",因此您可以使用->
运算符访问成员.
The expression tree
has type "pointer to struct Huffman
", so you use the ->
operator to access a member.
表达式 tree [i]
的类型为" struct Huffman
";下标运算符隐式取消引用指针(请记住,将 a [i]
评估为 *(a + i)
),因此您可以使用.
操作员访问成员.
The expression tree[i]
has type "struct Huffman
"; the subscript operator implicitly dereferences the pointer (remember that a[i]
is evaluated as *(a + i)
), so you use the .
operator to access a member.
基本上, a-> b
是(* a).b
的可读性更高的等效项.
Basically, a->b
is the somewhat more readable equivalent of (*a).b
.
这篇关于在c或c ++中用于树创建的结构对象变量在点运算符和箭头运算符之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!