I am unable to understand the weird behavior of this program. I have 2 files, file1.c and file2.c
file.c is
#include <stdio.h>struct ll {
int key;
struct ll *next;
};
extern void func(struct ll*);
int main(void)
{
struct ll l = { 1, &l };
printf("%d %d\n",l.key,l.next->key);
func(&l);
return 0;
}
and file2.c is:
#include <stdio.h>
struct ll
{
struct ll *next;
int key;
};
void func(struct ll *l)
{
printf("%d \n",l->key);
printf("%d \n",l->next->key);
}
Now when I compile and run it, it shows segmentation fault. But where as in file2.c if I replace struct ll with :
struct ll
{
int key;
struct ll *next;
};
Then it works fine. I mean just by interchanging the order of the declaration, it is impacting the output.
The declaration of the struct should be the same both times, since struct is just a layout of data in memory, and you switch the variables.
in your case, the code in the function
funcwill try to dereference the integer1set in the main function. (or maybe do other weird things, as int and pointer are not compatible)In file.c:
In file2.c: