为什么不编译

时间:2010-09-30 03:21:01

标签: c compiler-errors

#include <stdio.h>

typedef struct point{
    int x; 
    int y;
};

void main (void){

    struct point pt;
    pt.x = 20;
    pt.y = 333;

    struct point pt2;
    pt2.y = 55;

    printf("asd");
    return;
}

VS 2008

c:\documents and settings\lyd\mis documentos\ejercicio1.c\ejercicio1.c\ejercicio1.c(14) : error C2143: syntax error : missing ';' before 'type'
c:\documents and settings\lyd\mis documentos\ejercicio1.c\ejercicio1.c\ejercicio1.c(15) : error C2065: 'pt2' : undeclared identifier
c:\documents and settings\lyd\mis documentos\ejercicio1.c\ejercicio1.c\ejercicio1.c(15) : error C2224: left of '.y' must have struct/union type
Build log was saved at "file://c:\Documents and Settings\LYD\Mis documentos\ejercicio1.c\ejercicio1.c\Debug\BuildLog.htm"
ejercicio1.c - 3 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

4 个答案:

答案 0 :(得分:3)

删除typedef一词。

答案 1 :(得分:3)

它在我的gcc 4.4.3上编译得很好。

但是,您正在尝试定义新类型:

typedef struct point{
    int x; 
    int y;
};

但似乎你忘了给这个新类型命名(我只是称之为 point_t ):

typedef struct point{
    int x; 
    int y;
} point_t;

稍后,在您的代码中,您可以使用它:

point_t pt;
pt.x = 20;
pt.y = 333;

答案 2 :(得分:3)

由于问题标记为C(而不是C ++),并且由于编译器是MSVC 2008,因此您仍然坚持使用C89语义。这意味着您不能在第一个语句之后在块中声明变量。因此,那里不允许第二个struct变量。 (C99和C ++都允许您在块中的任何位置声明变量。请告诉MS更新其C编译器以支持C99。)

您的另一个错误是main()返回int,因此:

#include <stdio.h>

struct point
{
    int x; 
    int y;
};

int main (void)
{
    struct point pt;
    struct point pt2;
    pt.x = 20;
    pt.y = 333;
    pt2.x = 4;
    pt2.y = 55;
    printf("asd");
    return 0;
}

几个小时后:代码中不需要关键字typedef,因为在close括号之后和分号之前没有指定名称。这并不能阻止它编译;它将引发编译器设置繁琐的警告。

答案 3 :(得分:0)

尝试将pt2的声明移到函数顶部。有些C编译器需要声明为全局或代码块的开头。