c - 指向结构的指针和自指针

标签 c algorithm pointers structure

结构中的自引用指针和指向结构的指针有什么区别?

    struct abc
    {
    int data;
    struct abc *next;
    }
    struct abc *pt;
  1. *next*pt有什么区别??

  2. 它们在使用上有何不同?

我在这两个之间犹豫不决

我是初学者

第一个例子主要用于链表

指向结构节点的指针和自引用指针是一回事吗?

please see

see-programming.blogspot.in/2013/05/chain-hashing-separate-chaining-with.html 在这里我们使用了 struct hash *hashTable 作为数组......如何?我们可以用 *pt 做同样的事情吗

最佳答案

  1. 它们属于同一类型。它们的行为方式完全相同。

    一些示例用法:

    // 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;
    
  2. 用法差异:

    • 只有一个 pt 变量。

    • 对于每个 struct abc 变量,都有一个 next 变量。

    在链表的上下文中,只有一个头指针,因此 pt 就是它。
    但是每个节点都指向下一个节点,因此应该使用 next

  3. 将指针用作数组?

    是的,这可以通过 ptnext 完成。

    指针只是指向内存中的一个地址。在该位置可以有任意数量的结构相互跟随。

    如果你想将它用作一个数组(或者只是一般地使用指针),你只需要确保你不尝试访问你没有分配内存的元素(使用 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);
    

希望对您有所帮助。

关于c - 指向结构的指针和自指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18451788/

相关文章:

c - 如何使用数组将句子分成单词

c++ - 复合Simpson规则代码不断输出错误?

c++ - matlab 函数 "imfill(BW,' 孔的有效实现')“在 c++ 中不使用 opencv

c - C 中的结构体指针

C:判断数组内部是否存在指针并打印以下项目

c - 高效的手动循环展开

c - size_t 的长度不正确?

c - 显式多线程 SIMD 操作的最快方法是什么?

algorithm - 各种算法的示例输入

c++ - 通过引用的函数指针数组