问题
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.
These are the structs i wrote.
typedef struct vector{int x;int y;}Vector;
typedef struct VectorList{Vector X; struct VectorList*next; }node_v;
I globally defined a P vector and linked list of vectors prev.
Vector P;
node_v * prev=NULL;
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.
This is that part of the code.
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;
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;
}
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?
回答1:
The new node is created in the function append
:
node_v* new_node = (node_v*) malloc(sizeof(node_v));
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.
Remove if:
case GLUT_LEFT_BUTTON :
px=x;py=y;
P.x=x;
P.y=y;
append(&prev,P);
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;
}
来源:https://stackoverflow.com/questions/61527670/adding-coordinates-of-clicks-with-glut-to-a-linked-list-of-vectors