结构指针和自指针 [英] pointer to structure and self pointers
问题描述
结构中的自引用指针和结构指针之间有什么区别?
struct abc
{
int data;
struct abc *next;
}
struct abc *pt;
-
*next
和*pt
?? 有什么区别
-
它们的用法有何不同??
我真的怀疑这两者之间
我是初学者
第一个示例主要用于链接列表
结构节点的指针和自引用指针是否相同?
请参阅 >
see-programming.blogspot.in/2013/05/chain-hashing-separate-chaining-with.html在这里,我们使用结构哈希* hashTable作为数组..how?我们可以用* pt
做同样的事情吗
-
它们是同一类型.它们的行为完全相同.
一些用法示例:
// declare 2 structs struct abc s1; struct abc s2; // point pt to s1 pt = &s1; // point s1.next to s2 s1.next = &s2; // access pt->data int a = pt->data; // access s1.next->data int a = s1.next->data;
-
用法上的差异:
-
只有一个
pt
变量. -
对于每个
struct abc
变量,都有一个next
变量.
在链接列表的上下文中,只有一个头指针,因此将是
pt
.
但是每个节点都指向下一个节点,因此应使用next
. -
-
使用指针作为数组吗?
是的,可以使用
pt
或next
完成.指针仅指向内存中的地址.在该位置可以有任意数量的结构.
如果要使用它作为数组(或通常只使用指针),则只需确保不尝试访问未为其分配内存的元素(例如,使用
malloc
),并在使用后释放内存(如果您使用的是malloc
).一些使用数组的示例:
// declare a struct struct abc s1; // make an array of size 10 struct abc *a1 = malloc(10*sizeof(struct abc)); // give the 4th element a new value a1[4] = s1; // free the memory free(a1);
我希望能有所帮助.
What is the difference between self referential pointer in structure and pointer to structure?
struct abc
{
int data;
struct abc *next;
}
struct abc *pt;
What are the differences between
*next
and*pt
??How they differ in their use??
I am really in doubt between these two
I am a beginner
First example is used mainly for linked list
Are pointer to structure node and self referential pointer the same thing?
see-programming.blogspot.in/2013/05/chain-hashing-separate-chaining-with.html here we have used struct hash *hashTable as an array ..how?? and can we do same with *pt
They are of the same type. They behave in the exact same way.
Some example usage:
// declare 2 structs struct abc s1; struct abc s2; // point pt to s1 pt = &s1; // point s1.next to s2 s1.next = &s2; // access pt->data int a = pt->data; // access s1.next->data int a = s1.next->data;
Differences in usage:
There's only one
pt
variable.For every
struct abc
variable, there is anext
variable.
In the context of a linked-list, there is only one head pointer, thus
pt
would be it.
But each node points to the next node, thusnext
should be used for this.Using pointers as arrays?
Yes, this can be done with either
pt
ornext
.A pointer just points to an address in memory. There can be any number of structs following on each other at that location.
If you want to use it as an array (or just using pointers in general), you just have to make sure you don't try to access elements that you didn't allocate memory for (with
malloc
for example) and free the memory after usage (if you usedmalloc
).Some example usage with array:
// declare a struct struct abc s1; // make an array of size 10 struct abc *a1 = malloc(10*sizeof(struct abc)); // give the 4th element a new value a1[4] = s1; // free the memory free(a1);
I hope that helps a bit.
这篇关于结构指针和自指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!