#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node *link;
(*link).val = 12; // error
};
int main()
{
struct Node *link=(struct Node*)malloc(sizeof(struct Node));
(*link).val = 15; // OK
return 0;
}
Why am I getting an error when trying to access (*link).val inside the struct, while the same thing is working just fine in the main function?
You may declare members of a structure but you may not use statements (in C++ there can be declaration statements) within a structure declaration in C and C++ like for example that
A structure declaration may contain only declarations.
And in C opposite to C++ even member declarations may not have initializers. That is you may not write in C
Pay attention to that this code snippet
invokes undefined behavior because the pointer
linkis uninitialized and has an indeterminate value.Instead you could write for example