【问题标题】:Structures portions as argument: unknown type name结构部分作为参数:未知类型名称
【发布时间】:2015-04-06 23:13:38
【问题描述】:

我正在尝试将结构部分作为参数传递。但是,我在编译时收到以下消息:“未知类型名称'time1'”。这是导致这些问题的代码部分:

#include <stdio.h>

struct time {
    int hour;
    int minutes;
    int seconds;
};

struct time time1;
struct time time2;
struct time elapsed;

int hourDif (time1.hour, time2.hour) {
    if (time2.hour >= time1.hour) {
        elapsed.hour = time2.hour - time1.hour;
    }
    else {
        elapsed.hour = 24 - (time1.hour - time2.hour);
    }
    return 0;
}

【问题讨论】:

  • 函数定义需要每个参数的类型和名称。你什么都没有给出——你给出了实际数据,就像你在调用函数而不是定义它一样。

标签: c function structure


【解决方案1】:

这个

int hourDif (time1.hour, time2.hour)

不是函数调用,它是函数声明,在你的情况下它也是它的定义,你需要的是

int hourDif (struct time time1, struct time time2)
 {
    int difference;
    difference = 0; /* some compilers might complain */
    if (time2.hour >= time1.hour)
        difference = time2.hour - time1.hour;
    else
        difference = 24 - (time1.hour - time2.hour);
    return difference;
}

然后在代码中的某个地方,不需要全局变量

struct time time1;
struct time time2;

/* initialize `time1' and `time2' */
int difference  = hourDiff(time1, time2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    相关资源
    最近更新 更多