将带有glut的点击的坐标添加到向量的链接列表中 [英] Adding coordinates of clicks with glut to a linked list of vectors
问题描述
我想创建矢量的链接列表,并借助GLUT库获取点击位置并将其附加到链接列表中.
I want to create a linked list of vectors and with the help of GLUT library get the positions of the clicks and append them to the linked list.
这些是我写的结构.
typedef struct vector{int x;int y;}Vector;
typedef struct VectorList{Vector X; struct VectorList*next; }node_v;
我全局定义了一个P向量和上一个向量的链接列表.
I globally defined a P vector and linked list of vectors prev.
Vector P;
node_v * prev=NULL;
每次单击鼠标左键时,都在鼠标回调函数_mouse_CB中,我想用当前的x和y值更新P向量,并将它们附加到链接列表中.
Inside the mouse callback function _mouse_CB everytime left mouse button is clicked, i want to update the P vector with the current x and y values and append them to the linked list.
这是代码的一部分.
static void _mouse_CB(int button, int state, int x, int y)
{
if(state==GLUT_DOWN)
{
switch(button)
{
case GLUT_LEFT_BUTTON :
px=x;py=y;
P.x=x;
P.y=y;
prev=VL_new1(P);
append(&prev,P);
break;
我在这里用geeksforgeeks编写的append函数,并在末尾添加了while循环,以检查值是否正确添加,但是我越来越溢出.
the append function here i wrote from geeksforgeeks and added a while loop at the end to check if the values are added correctly, but i am getting overflow.
void append(node_v** head_ref, Vector A)
{
node_v* new_node = (node_v*) malloc(sizeof(node_v));
node_v *last = *head_ref;
new_node->X.x = A.x;
new_node->X.y = A.y;
new_node->next = NULL;
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
last = *head_ref;
while(last){
printf("%d %d\n", last->X.x,last->X.y);
last = last->next;
}
return;
}
要创建一个节点,我编写了此函数
To create a node i wrote this function
node_v* VL_new1(Vector A){
node_v *new = (node_v*)malloc(sizeof(node_v));
if(new==NULL){exit(1);}
else{
new->X.x = A.x;
new->X.y = A.y;
new->next = NULL;
}
return new;
}
每次我运行该程序并单击出现的窗口时,在终端上,appendf里面的printf都会输出此
Each time i run this program and click on the appeared window, on the terminal the printf inside append function outputs this
-732680176 -729092496
0 -1344244448
我应该进行哪些更改以免溢出并成功添加当前值?
What changes should i make to not get overflow and successfully add the current values?
推荐答案
新节点在函数append
中创建:
node_v* new_node = (node_v*) malloc(sizeof(node_v));
指令prev=VL_new1(P);
生成一个新的列表头.每次执行代码时,都会设置prev
,并且prev
的先前内容会丢失.
The instruction prev=VL_new1(P);
generates a new list head. Every time when the code is executed, then prev
is set and the previous content of prev
is lost.
删除是否:
case GLUT_LEFT_BUTTON :
px=x;py=y;
P.x=x;
P.y=y;
append(&prev,P);
请注意,函数VL_new1
可以在append
中调用,而不是:
Note, the function VL_new1
can be called in append
, instead:
void append(node_v** head_ref, Vector A)
{
node_v *last = *head_ref;
node_v* new_node = VL_new1(A);
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
}
这篇关于将带有glut的点击的坐标添加到向量的链接列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!