我无法理解这个程序的奇怪行为。我有 2 个文件,file1.c 和 file2.c
文件.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);
}
现在,当我编译并运行它时,它显示段错误。但是在 file2.c 中,如果我将 struct ll 替换为:
struct ll
{
int key;
struct ll *next;
};
然后就可以正常工作了。我的意思是,仅仅通过交换声明的顺序,它就会影响输出。
最佳答案
两次结构体的声明应该相同,因为结构体只是内存中数据的布局,并且您可以切换变量。
在您的情况下,函数func
中的代码将尝试取消引用主函数中设置的整数1
。 (或者可能做其他奇怪的事情,因为 int 和指针不兼容)
在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
关于c - 改变输出的结构声明顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9961908/