0

i need to create a struct with an attribute that is a pointer to the same struct.

i'm trying this solution but not work:

    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);
}

can someone help me? best regards and thankyou

3 Answers3

2

I'm not entirely sure but are you looking for some sort of linked-lists or precisely speak Self Referential structure

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

Here is another good reference what-is-self-referencing-structure-in-c


just a little bit simplification, and moving few instructions here and there, below code is a loosely written example of possibly what you are looking forward to achieve

#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;
}
asio_guy
  • 3,667
  • 2
  • 19
  • 35
2

In C, you can name the struct before using it and typdefing it:

typedef struct mystruct_
{
    int number;
    struct mystruct_ *other;
} mystruct
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
0

your first and second don't need to be extern as they are allocated within your program. you can declare and init. var prior to the main. but the rest you must move into the main function:

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;}
H.cohen
  • 517
  • 3
  • 9
  • Should be a comment, not an answer. – Matthieu Brucher Oct 21 '18 at 09:33
  • @MatthieuBrucher thank you, I am new here and would love it if you can point me to the reason why and where its written so going forward I will use comments and answers correctly – H.cohen Oct 21 '18 at 09:36
  • It doesn't solve the problem raised by OP. If you have comments (and I agree with you, these are relevant comments) on the code quality, they are welcome, but as comments, not answers. – Matthieu Brucher Oct 21 '18 at 09:51