2010-09-30 83 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編譯器需要聲明爲全局或在代碼塊的開始。