【问题标题】:struct in c with an attribute that is a pointer to the same structc中的结构,其属性是指向同一结构的指针
【发布时间】:2018-10-21 09:14:58
【问题描述】:

我需要创建一个结构,其属性是指向同一结构的指针。

我正在尝试这个解决方案,但不起作用:

    typedef struct
{
    int number;
    void *other;
}mystruct;

extern mystruct first[];
extern mystruct second[];

mystruct first[] = {{1,NULL},{2,second}};
mystruct second[] = {{3,NULL},{4,first}};

mystruct *wrap;
wrap = (mystruct *)first[1].other;

int main(void){
    printf("%d\n",first[0].number);
    printf("%d\n",second[0].number);
    printf("%d\n",wrap[1].number);
}

有人可以帮助我吗? 最好的问候和谢谢

【问题讨论】:

  • 换个说法:你为什么将firstsecond 声明为extern
  • 因为我的第一个测试没有 extern 就行不通!

标签: c struct


【解决方案1】:

我不完全确定,但您是在寻找某种 linked-lists 还是准确地说是 Self Referential structure

struct list {
   int something;
   struct list *use_this_to_point_to_similar_type;
};

这是另一个很好的参考what-is-self-referencing-structure-in-c


只是一点点的简化,并在这里和那里移动一些指令,下面的代码是一个写得很松散的例子可能是你期待实现的目标

#include<stdio.h>
struct mystruct
{
    int number;
    struct mystruct *other;
};


struct mystruct first[] = {{1,NULL},{2,NULL}};
struct mystruct second[] = {{3,NULL},{4,NULL}};
struct mystruct *wrap;

int main(void)
{
        first[1].other = second;
        second[1].other = first;
        wrap = first[1].other;

        printf("%d\n",first[0].number);
        printf("%d\n",second[0].number);
        printf("%d\n",wrap[1].number);

        return 0;
}

【讨论】:

    【解决方案2】:

    C 中,您可以在使用它之前命名该结构并typdefing 它:

    typedef struct mystruct_
    {
        int number;
        struct mystruct_ *other;
    } mystruct
    

    【讨论】:

      【解决方案3】:

      您的第一个和第二个不需要是 extern,因为它们是在您的程序中分配的。你可以声明和初始化。 var 在 main 之前。但其余的你必须进入主函数:

      int main(void){
      
      wrap = (first[1].other);
      
      printf("%d\n",first[0].number);  
      printf("%d\n",first[1].number); 
      printf("%d\n",second[0].number);
      printf("%d\n",wrap[1].number);
      return 0;}
      

      【讨论】:

      • 应该是评论,而不是答案。
      • @MatthieuBrucher 谢谢你,我是新来的,如果你能指出为什么以及在哪里写的原因,我会喜欢它,所以我会正确使用 cmets 和答案
      • 它并没有解决OP提出的问题。如果您在代码质量上有 cmets(我同意您的观点,这些是相关 cmets),欢迎他们,但作为 cmets,而不是答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      相关资源
      最近更新 更多