2010-09-30 78 views
0
#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为什么isn't这个编译

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 ========== 
+1

你应该说你正在使用哪个编译器以及这个消息是什么。 – 2010-09-30 03:24:41

+0

好奇地类似于http://stackoverflow.com/questions/35333/compiler-error-c2143-when-using-a-struct – 2010-09-30 03:52:37

回答

3

由于问题被标记为C(而不是C++),并且由于编译器是MSVC 2008,所以您被C89语义卡住了。这意味着你不能在第一个语句之后的块中声明变量。因此,第二个结构变量不允许在那里。 (两个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。这并不能阻止它编译;它会引发一个警告与编译器集挑剔。

+0

是的,将声明移到顶端使其工作。谢谢! – DanC 2010-09-30 03:43:50

3

删除单词typedef

+0

删除typedef后仍然没有编译 – DanC 2010-09-30 03:28:32

+0

删除typedef后:(14):错误C2143 :语法错误:缺少';'在'type'之前 – DanC 2010-09-30 03:29:05

+1

在任何语句之前移动'pt'和'pt2'的变量声明。 MSVC不支持C99。 – 2010-09-30 03:36:38

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; 
+0

由于'* _t'由POSIX保留,''point_t'对类型名称来说是一个坏主意。 – 2010-09-30 03:35:21

+0

GCC 4.4.3支持C99; MSVC 2008没有。 – 2010-09-30 03:41:11

+0

GCC将给出警告:ISO C90禁止混合声明和代码。 – 2010-09-30 03:42:55

0

尝试移动dec将pt2置于该函数的顶部。一些C编译器需要声明为全局或在代码块的开始。