简体   繁体   中英

Order of declaration of struct changing the output

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 func will try to dereference the integer 1 set in the main function. (or maybe do other weird things, as int and pointer are not compatible)

In file.c :

struct ll: [ int (key)   | pointer (next) ]
struct ll l = { 1, &l }; // this causes:
l:         [ 1           | &l             ]

In file2.c :

struct ll: [ pointer (next) | int (key)   ]
// so the passed struct is treated in the same way:
l:         [ 1           | &l             ]
              next          key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM