+ -
当前位置:首页 → 问答吧 → C语言结构体指针的初始化问题

C语言结构体指针的初始化问题

时间:2011-12-13

来源:互联网

#include<stdio.h>
struct student
{
int num;
int score;
};
struct student stu;
struct student *p;
p=&stu;
int main()
{
return 0;
}

编译后:
--------------------Configuration: 123 - Win32 Debug--------------------
Compiling...
123.cpp
c:\documents and settings\administrator\123.cpp(8) : error C2501: 'p' : missing storage-class or type specifiers
c:\documents and settings\administrator\123.cpp(8) : error C2040: 'p' : 'int' differs in levels of indirection from 'struct student *'
c:\documents and settings\administrator\123.cpp(8) : error C2440: 'initializing' : cannot convert from 'struct student *' to 'int'
  This conversion requires a reinterpret_cast, a C-style cast or function-style cast
Error executing cl.exe.

123.obj - 3 error(s), 0 warning(s)


但是以下代码在编译时不会报错:
struct student
{
int num;
int score;
};
struct student stu,*p=&stu;;
int main()
{
return 0;
}
--------------------Configuration: 123 - Win32 Debug--------------------
Compiling...
123.cpp

123.obj - 0 error(s), 0 warning(s)

请高手指点迷津,谢谢!#include<stdio.h>

作者: wxliu619   发布时间: 2011-12-13

语句得写到函数中
C/C++ code
#include<stdio.h>
struct student
{
 int num;
 int score;
};
struct student stu;
struct student *p;
int main()
{
   p=&stu;
}

作者: akirya   发布时间: 2011-12-13

定义可以写在函数外面
C/C++ code

struct student stu,*p=&stu;;

作者: dongjiawei316   发布时间: 2011-12-13

p=&stu;如果是像这样的语句应该写在函数体里面,不能写在函数体外面,
struct student stu,*p=&stu;是初始化的时候就给指针赋除值,这样是可以的。

作者: liru125504   发布时间: 2011-12-13