Bogdan Molinger
Bogdan Molinger

Reputation: 341

Array of pointers which point to themselves

I found an interesting exercise which says the following:

Write a type in C containing an array of pointers which point to the type itself

Now I'm not really sure what it refers to. Does it ask for something like

struct a {
    struct *b[];
}   

int main(void) {  
    struct b[20]*;
    for(i=0;i<19;i++)  
        b[i]=&b[i];  
}

Can it be written like this ?

Upvotes: 0

Views: 153

Answers (2)

Matt Phillips
Matt Phillips

Reputation: 9691

The question is asking for something like this:

#include <stdio.h>

struct A
{
    struct A* b[5];
};

int main(void) 
{
    struct A a;
    int i;
    for (i=0; i<5; ++i)
         a.b[i] = &a;
    return 0;
}

Presumably, the point is that a type does not need to be complete, just declared, before you can declare a pointer to it.

Upvotes: 1

sepp2k
sepp2k

Reputation: 370357

No, the exercise is not asking for the pointer to point to itself. It says "the type itself". So all it's saying is that the array should contain pointers that point to values of type struct a. It doesn't matter to which address the pointers actually point.

Upvotes: 4

Related Questions