在C89中通过指针传递结构体

3

我是一名使用C89编译器的开发者,最近遇到了一些指针类型错误。

调用代码如下:

struct cpu_state_type cpu_state;
//Stuff here....
foo()
{
    print_out_cpu(&cpu_state);
}

Print_out_cpu在其他地方被定义,而且H文件已经被包含进来了。

struct cpu_state_type
{
  int r[12];
};
void print_out_cpu(struct cpu_state_type *c);

我遇到了错误:

error: ‘print_out_cpu’的第1个参数类型不兼容

据我所知,&cpu_state返回的类型是cpu_state_type*,所以我很困惑。


你能否尝试将其转换为 (cpu_state_type*) 然后看是否能正常运行或崩溃? - pajton
struct cpu_state_type的定义在哪里? - Bertrand Marron
Python:在进行强制类型转换时出现错误。添加(struct cpu_state_type*)可以使其更好地工作,但是然后会说找不到print_out_cpu(!!)。 - Paul Nathan
1
“添加一个转换并查看是否有效”绝对不能作为解决问题的答案。 - nos
2
@Paul:你说使用显式转换为struct cpu_state_type*时,print_out_cpu函数没有匹配项 - 这让我想到你在某个地方有冲突的声明。 - Nikolai Fetissov
1
@nos 我正在尝试获取有关问题的更多信息。如果我认为这是一个解决方案,我会将其发布为答案。 - pajton
2个回答

1

你确定原型中有*吗?如果我编译以下代码(gcc -std=c89),我会得到完全相同的错误:

  struct cpu_state_type {
     int r[12];
  };

  // note that it is the structure as the param here (not the pointer)
  void print_out_cpu(struct cpu_state_type c);
  struct cpu_state_type cpu_state;

  foo()
  {
     print_out_cpu(&cpu_state);
  }

0

我没有看到任何问题,所以我想知道是你的包含语句或文件中出现了错误等。

如果没有看到更多源代码,很难确定错误的原因。尝试创建一个源文件,例如:

#include struct cpu_state_type cpu_state;

void foo() {
print_out_cpu(&cpu_state); }

如果这不会触发问题,请继续添加内容直到触发问题为止。 如果它确实触发了问题,请将头文件的相关部分提取到您的源代码中(并删除 #include),然后再次尝试。


4
包含结构体cpu_state_type的定义后,声明了一个名为cpu_state的变量。 - Bertrand Marron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接