几个c问题:静态方法、数组
我正在做一个C语言的项目,偶然发现了几个问题,希望你们这些优秀的人能帮助我!项目只是操纵用户通过标准输入创建的坐标点。我在下面介绍了不同的文件及其功能几个c问题:静态方法、数组,c,arrays,static,C,Arrays,Static,我正在做一个C语言的项目,偶然发现了几个问题,希望你们这些优秀的人能帮助我!项目只是操纵用户通过标准输入创建的坐标点。我在下面介绍了不同的文件及其功能 //points.h struct Point{ int x; int y; } //reads points from stdinput into our points array int pointReader(struct Point points[]); /////////////// //points.c void p
//points.h
struct Point{
int x;
int y;
}
//reads points from stdinput into our points array
int pointReader(struct Point points[]);
///////////////
//points.c
void pointReader(struct Point points[]){
//points[] is originally empty array (filled with NULLS)
struct Point point;
char buffer[10];
printf("X Coordinate:");
fgets(buffer, 10, stdin);
point.x = (int)buffer;
printf("Y Coordinate:");
fgets(buffer, 10, stdin);
point.y = (int)buffer;
append(points, point);
}
static void append(struct Point points[], struct Point point){
int i;
for (i = 0; i < 10; i++){
if (points[i] == NULL){
points[i] = point;
}
另外,我是否可以像我尝试做的那样轻松地在点[]
数组中“抛”来抛去
谢谢你的评论 第一个错误很可能是因为在调用函数之前没有声明函数append
。在调用之前添加一个函数原型。换句话说,在读点器定义之前,添加以下行:
static void append(struct Point points[], struct Point point);
第二个错误是因为points
数组中的值不是指针,因此不能像指针一样处理(比如将其与NULL
进行比较)。您必须使用另一种方法来检查数组中的条目是否被使用。例如,使用-1
的x
和y
值或类似值
您还有另一个问题,那就是不能通过强制转换将字符串转换为整数。您必须使用如下函数:
point.x = (int) strtol(buffer, NULL, 10);
好的,那么也许只是先用0填充数组的每个索引,然后检查0就行了?@FrankyJ542除非0
是有效值,那么是的。理解了Joachim,非常感谢您的帮助。对我对点阵列的操作有何评论?我希望我所要做的足够清楚@FrankyJ542你的代码还有另一个问题,我更新了我的答案。否则看起来没问题。
point.x = (int) strtol(buffer, NULL, 10);