c - 改变输出的结构声明顺序

标签 c procedural-programming

我无法理解这个程序的奇怪行为。我有 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/

相关文章:

c - 使用 write() 从整数数组中写入元素

c - 如何将任意大文件读取到 C 中的 TCP 套接字?

c - 查找与特定位置上的另一个字符串匹配的字符串,忽略其他字符串(C 字符串)

php - 自定义错误处理程序,用于处理对象代码内部和外部的错误

javascript - JavaScript 中的过程方法

c - 我将如何 'spawn' 或按程序实例化多个生物?

嵌入式 Web 服务器中的 CRUD

在 C-mbed 平台中每 10 秒调用一个函数

oop - 为什么 OOP 与过程编程并列?