通过函数传递结构时收到警告

Getting a warning when passing struct through function

我正在尝试按值通过函数传递整个结构,并通过显示传递的结构中的变量来测试传递是否成功。

当我编译和 运行 程序时,变量显示正确,但我收到警告:

warning: parameter names (without types) in function declaration

所以它指的是用没有类型的参数名称声明的函数原型?但是,如果我正确地声明了函数,为什么会收到此警告?

此外,在我编写的用于测试这个的短程序中,警告不会影响显示的输出是正确的。

但是如果我在编写更大规模的程序时在相同情况下(通过函数传递结构)收到此警告,是否会影响该程序的输出正确性?

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void pass(Info);

typedef struct {
    char str[10];
    int num;
} Info;

void main() {
    Info i;

    strcpy(i.str, "Hello!");
    i.num = 1;

    pass(i);
}

void pass(Info i) {
    printf("%s\n", i.str);
    printf("%d\n", i.num);
}

输出:

Hello!

1

你有typedef声明使用新定义的类型(另一种类型的同义词,挑剔).那时,在函数前向声明中,编译器不知道名为 Info 的类型。因此,它假定它是一个变量名。

typedef 移到函数原型之前。

也就是说,void main() 不是托管环境中 main() 的有效签名。至少应该是int main(void)

因为你是在Info结构声明之前声明函数原型。

替代方法可以是以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct 
{
    char str[10];
    int num;
} Info;

void pass(Info);

void main() 
{
      Info i;

      strcpy(i.str, "Hello!");
      i.num = 1;
      pass(i)
}

void pass(Info i) 
{
     printf("%s\n", i.str);
     printf("%d\n", i.num);
}

编译器考虑这个函数声明

void pass(Info);

作为带有标识符列表的函数声明。那就是这里 Info 是参数的标识符而不是它的类型。

但是根据 C 标准(6.7.6.3 函数声明符(包括原型)):

3 An identifier list in a function declarator that is not part of a definition of that function shall be empty.

因此编译器发出警告,指出对于不是函数定义的函数声明,标识符列表不为空。

warning: parameter names (without types) in function declaration

要么你写

void pass();

或者您应该将结构声明的 typedef 放在函数声明之前,在这种情况下,名称 Info 将表示一个类型。