在C中初始化结构时出错

时间:2012-09-28 15:30:03

标签: c

尝试编译使用结构的C源文件时出错。 我在Ubuntu 12.04 LTS上使用gcc(Ubuntu / Linaro 4.6.3-1ubuntu5)4.6.3。

以下是代码:

/* struct.c: Illustrates structures */
#include <stdio.h>
#include <string.h>

struct Hitter {
    char last[16];
    char first[11];
    int home_runs;
};

int main() {
    struct Hitter h1 = {"McGwire", "Mark", 70};
    struct Hitter h2;
    strcpy(h2.last, "Sosa");
    strcpy(h2.first, "Sammy");
    h2.home_runs = h1.home_runs - 4;
    printf("#1 == {%s, %s, %d}\n",
           h1.last, h1.first, h1.home_runs);
    printf("#2 == {%s, %s, %d}\n",
           h2.last, h2.first, h2.home_runs);
    return 0;
}

这是错误:

$ gcc -o struct struct.c
struct.c: In function `main':
struct.c:12:9: error: parameter `h1' is initialized
struct.c:14:2: error: expected declaration specifiers before `strcpy'
struct.c:15:2: error: expected declaration specifiers before `strcpy'
struct.c:16:2: error: expected declaration specifiers before `h2'
struct.c:18:2: error: expected declaration specifiers before `printf'
struct.c:21:2: error: expected declaration specifiers before `printf'
struct.c:23:2: error: expected declaration specifiers before `return'
struct.c:24:1: error: expected declaration specifiers before `}' token
struct.c:13:16: error: declaration for parameter `h2' but no such parameter
struct.c:12:16: error: declaration for parameter `h1' but no such parameter
struct.c:24:1: error: expected `{' at end of input

以上代码来自Chuck Allison的CD培训课程“Thinking in C”。我知道这是一张很老的CD,我确信结构的语法必须改变,但我不知道它现在是什么。非常感谢您的帮助。 感谢

1 个答案:

答案 0 :(得分:1)

一旦我遇到了类似的情况,结果我试图编译的文件有不正确的行结尾。例如,从磁盘获取的文件可能具有CR + LF作为行尾,而只需要LF。通过选择在大多数文本编辑器中显示不可见字符,可以发现这一点。