还是结构体指针的问题
程序1;
#include <stdio.h>
#include <malloc.h>
int main(){
struct point {
int x;
int y;
} ;
struct point* setpoint(int inx, int iny){
struct point* pp = malloc(sizeof(struct point));
pp -> x = inx;
pp -> y = iny;
return pp;
}
void pointPrint(struct point* pointPt){
printf( "id: %d name: %d\n ",pointPt -> x, pointPt -> y);
}
struct point* p = setpoint(1,2);
pointPrint(p);
return 0;
}
ok,编译运行输出都正常
我把两个函数setpoint和pointPrint写在main函数外面,也就是
程序2
#include <stdio.h>
#include <malloc.h>
int main(){
struct point {
int x;
int y;
} ;
struct point* setpoint(int inx, int iny);
void pointPrint(struct point* pointPt);
struct point* p = setpoint(1,2);
pointPrint(p);
return 0;
}
struct point* setpoint(int inx, int iny){
struct point* pp = malloc(sizeof(struct point));
pp -> x = inx;
pp -> y = iny;
return pp;
}
void pointPrint(struct point* pointPt){
printf( "id: %d name: %d\n ",pointPt -> x, pointPt -> y);
}
问题来了
test.c:19: 错误:与 ‘setpoint’ 类型冲突
test.c:10: 错误:‘setpoint’ 的上一个声明在此
test.c: 在函数 ‘setpoint’ 中:
test.c:20: 错误:‘sizeof’ 不能用于不完全的类型 ‘struct point’
test.c:21: 错误:提领指向不完全类型的指针
test.c:22: 错误:提领指向不完全类型的指针
test.c: 在顶层:
test.c:26: 错误:与 ‘pointPrint’ 类型冲突
test.c:11: 错误:‘pointPrint’ 的上一个声明在此
test.c: 在函数 ‘pointPrint’ 中:
test.c:27: 错误:提领指向不完全类型的指针
test.c:27: 错误:提领指向不完全类型的指针
俺实在不太明白。。不是可以前面声明后面使用么?
[解决办法]
先别说第二个程序吧。。
第一个程序楼主可以正常编译?请问楼主用的是哪个平台?
在下用VC++6.0和WIN-TC都没有正常编译!!!!
从楼主写的这两个(姑且这样说吧)程序来看,楼主对变量的作用域不太熟悉,而且对malloc函数也不熟悉,malloc函数返回的是void类型。struct point* pp = malloc(sizeof(struct point));这一句显然会造成类型不符,应改为struct point* pp = (struct point *)malloc(sizeof(struct point));
修改程序如下(在WIN-TC或vc++6.0下正常编译):
/* #include <iostream.h> 在VC++6.0需要此句*/
#include <stdio.h>
#include <malloc.h>
struct point{
int x;
int y;
};
struct point *setpoint(int inx,int iny)
{/* 该函数返回一个结构体指针 */
struct point *pp=(struct point *)malloc(sizeof(struct point));
/* (struct point *) 表示强制类型转换 */
pp-> x=inx;
pp-> y=iny;
printf( "pp-> x=%d,pp-> y=%d\n ",pp-> x,pp-> y);
}
int main()
{
int xx=5,yy=10; /* xx,yy也可用scanf语句自行取值 */
setpoint(xx,yy);
getch(); /*在VC++6.0下请去除此句*/
return 0;
}
===或修改为(注意点同上):
#include <stdio.h>
#include <malloc.h>
struct point
{
int x;
int y;
};
struct point *setpoint(int inx, int iny);
void pointPrint(struct point *pointPt);
int main()
{
struct point * p = setpoint(1,2);
pointPrint(p);
getch();
return 0;
}
struct point *setpoint(int inx, int iny)
{
struct point *pp = (struct point *)malloc(sizeof(struct point));
pp -> x = inx;
pp -> y = iny;
return pp;
}
void pointPrint(struct point *pointPt)
{
printf( "id: %d name: %d\n ",pointPt -> x, pointPt -> y);
}