Why isn´t this compiling
#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 ==========
Since the question is tagged C (and not C++), and since the compiler is MSVC 2008, you are stuck with C89 semantics. That means you cannot declare variables in a block after the first statement. Hence, the second struct variable is not allowed there. (Both C99 and C++ allow you declare variables at any point in the block. Go tell MS to update their C compiler to support C99.)
Your other bug is that main()
returns an int
, hence:
#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;
}
Some hours later: the keyword typedef is not needed in the code because no name is specified after the close brace and before the semi-colon. This doesn't stop it compiling; it will elicit a warning with the compiler set fussy.
Remove the word typedef
.
It compiles just fine on my gcc 4.4.3.
However, you are trying to define a new type:
typedef struct point{
int x;
int y;
};
but it seems you forgot to name this new type (I'll just call it point_t):
typedef struct point{
int x;
int y;
} point_t;
Later, on your code, you could use it like:
point_t pt;
pt.x = 20;
pt.y = 333;
Try moving the declaration of pt2
to the top of the function. Some C compilers require declarations to either be global or at the start of a code block.
精彩评论