繁体   English   中英

结构更改输出的声明顺序

[英]Order of declaration of struct changing the output

我无法理解该程序的怪异行为。 我有2个文件,file1.c和file2.c

file.c是

#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;
}

和file2.c是:

#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);
 }

现在,当我编译并运行它时,它显示了分段错误。 但是,如果将struct ll替换为file2.c中的位置:

struct ll 
{
 int key;   
 struct ll *next;       
};

然后工作正常。 我的意思是仅通过更改声明的顺序,它就会影响输出。

两次结构声明都应该相同,因为struct只是内存中数据的布局,并且您可以切换变量。

在您的情况下,函数func的代码将尝试取消引用主函数中设置的整数1 (或者做其他奇怪的事情,因为int和pointer不兼容)

file.c中

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

file2.c中

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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