代码的一个版本可能是:
typedef struct Position
{
int x;
int y;
} Position;
typedef struct PosnList
{
size_t num_pts;
size_t max_pts;
Position *points;
} PosnList;
void add_point(int x, int y, PosnList *p)
{
if (p->num_pts >= p->max_pts)
{
size_t new_num = (p->max_pts + 2) * 2;
Position *new_pts = realloc(p->points, new_num * sizeof(Position));
if (new_pts == 0)
...handle out of memory error...
p->max_pts = new_num;
p->points = new_pts;
}
p->points[p->num_pts++] = (Position){ x, y };
}
void zap_posnlist(PosnList *p)
{
free(p->points);
p->num_pts = 0;
p->max_pts = 0;
p->points = 0;
}
那么你的代码就可以了:
int x, y;
x = report.xbutton.x;
y = report.xbutton.y;
if (report.xbutton.button == Button1) {
XFillArc(display_ptr, win, gc_red,
x - win_height/80, y - win_height/80,
win_height/60, win_height/60, 0, 360*64);
add_point(x, y, &positions);
}
哪里有变量:
PosnList positions = { 0, 0, 0 };
注意add_point() 函数使用realloc() 来进行初始内存分配和增量内存分配。该代码使用 C99 复合文字将值 x 和 y 分配给数组中的下一个 Position。如果你没有 C99,你需要做两个单独的作业。
zap_posnlist() 函数释放先前初始化的PosnList。你可能仍然需要一个正式的初始化函数——除非你乐于在任何地方使用 PosnList xxx = { 0, 0, 0 }; 符号。
此代码现已被 GCC 清理;原来的版本不是,而且里面有错误——产生编译器错误的错误。
经过测试的代码 — 请注意,"stderr.h" 不是标准标头,而是我习惯使用的错误报告代码。它提供了err_error() 和err_setarg0() 函数。
#include <stdlib.h>
#include "stderr.h"
typedef struct Position
{
int x;
int y;
} Position;
typedef struct PosnList
{
size_t num_pts;
size_t max_pts;
Position *points;
} PosnList;
extern void add_point(int x, int y, PosnList *p);
extern void zap_posnlist(PosnList *p);
void add_point(int x, int y, PosnList *p)
{
if (p->num_pts >= p->max_pts)
{
size_t new_num = (p->max_pts + 2) * 2;
Position *new_pts = realloc(p->points, new_num * sizeof(Position));
if (new_pts == 0)
err_error("Out of memory (%s:%d - %zu bytes)\n",
__FILE__, __LINE__, new_num * sizeof(Position));
p->max_pts = new_num;
p->points = new_pts;
}
p->points[p->num_pts++] = (Position){ x, y };
}
void zap_posnlist(PosnList *p)
{
free(p->points);
p->num_pts = 0;
p->max_pts = 0;
p->points = 0;
}
#include <stdio.h>
int main(int argc, char **argv)
{
PosnList positions = { 0, 0, 0 };
err_setarg0(argv[0]);
if (argc > 1)
srand(atoi(argv[1]));
for (size_t i = 0; i < 37; i++)
add_point(rand(), rand(), &positions);
for (size_t i = 0; i < positions.num_pts; i++)
printf("%2zu: (%5d, %5d)\n", i, positions.points[i].x, positions.points[i].y);
zap_posnlist(&positions);
return(0);
}
如果您需要stderr.h 和stderr.c 的来源,请与我联系(查看我的个人资料)。