Thread: Struct delcaring a struct within itself question

1. Struct delcaring a struct within itself question

edit : ^^^ Title should be referring to a struct pointer, ty Stiltskin

Code:
```struct foo{
int num;
char *word;
struct foo *ptr;
};
void func1(struct foo);
void func2(struct foo*);
void func3(struct foo);

int main(){
...
...
a.ptr = &a;
a.num = 50;
a.word = "mylastword";
func3(a);
printf("4 %d %s\n", a.num, a.word);
...
}

void func3(struct foo a)
{
if(a.num > a.ptr->num)
{ a.num = 500; }
else
{ a.num = a.ptr->num + 1; }

a.word = "myotherword";
a.ptr->word = "yetanotherword";
printf("3  %d %s\n", a.num, a.word);
}```
Could someone explain to me what happened at the line with a.ptr = &a. It seems the compiled version showing the solution is using a.ptr = a.num so therefore a.num = 50+1

the printf prints 3 51 myotherword

did a.ptr take the following lines value?

2. You have two printf statements in the code you posted; you seem to be asking about the one in func3, because the output from the printf in main will be different.

The a in func3 is a local (exists only within func3) copy of the a in main. But the value of its pointer is the same as the value of the pointer in main's a, so it points to main's a.

So, inside func3, the statement a.word = "myotherword"; changes the string in the local copy of a. But the statement a.ptr->word = "yetanotherword"; changes the string in main's a, not the string in func3's a.

The if statement condition is false because num is the same in the original and the copy. The else statement: a.num = a.ptr->num + 1; changes only the num that belongs to func3's a, assigning to it the value of num in main's a plus 1.

edit: By the way, your struct doesn't "declare a struct within itself". It declares a struct pointer.

3. I believe I am following what you are saying but I am still confused on how the a.ptr-> word got a value equivalent to the a.num

I can change a.num to another number and the if statement would continue to fail and it prints a.ptr->num+1.

That number it is printing is always the value of a.num+1.

Or I guess a better way to ask is :
In the main part of the code, what is this line doing :

a.ptr = &a;

Much appreciated

4. a.ptr is a pointer to a struct foo. A pointer can contains the address of an object (i.e. a pointer to a struct foo can contain the address of an object of type struct foo).

The line a.ptr = &a sets a.ptr to contain the address of a. After that (a.ptr)->word is equivalent to (&a)->word which is also equivalent to a.word.

And this is not a struct declaring (or containing) a struct within itself. A struct is allowed to contain a pointer.

One analogy is a house containing a bit of paper describing the street address of the house. The street address identifies the house, but is not the house.