Answer the question
In order to leave comments, you need to log in
Why is the data in the struct overwritten?
Good day, I ask you to help with the following question.
There is a structure like this:
struct node
{
int Number;
nodecoordinates* Items;
};
struct edge
{
int Number;
edgecoordinates* Items;
};
struct model
{
struct node Node;
struct edge Edge;
};
struct view
{
struct model Model;
// остальные поля
};
int allocate_edges(struct view* View)
{
View->Model.Edge.Items = (edgecoordinates*)calloc(View->Model.Edge.Number, sizeof(edgecoordinates));
if (!View->Model.Edge.Items)
{
return CANT_ALLOCATE_EDGES;
}
else
{
return OK;
}
}
int allocate_nodes(struct view* View)
{
View->Model.Node.Items = (nodecoordinates*)calloc(View->Model.Node.Number, sizeof(nodecoordinates));
if (!View->Model.Node.Items)
{
return CANT_ALLOCATE_NODES;
}
else
{
return OK;
}
}
struct line
{
int x1, x2, y1, y2;
};
int allocate_lines(struct line* lines, int Number)
{
lines = (line*)malloc(Number*sizeof(struct line));
if (!lines)
{
return CANT_ALLOCATE_LINES;
}
return OK;
}
...
struct line lines;
error = allocate_lines(&lines, View.Model.Edge.Number);
void build_lines(struct view View, struct line* lines)
{
for (int i = 0; i < View.Model.Edge.Number; i++)
{
(lines + i)->x1 = (int)((View.Model.Node.Items + (View.Model.Edge.Items + i)->node1)->X);
(lines + i)->y1 = (int)((View.Model.Node.Items + (View.Model.Edge.Items + i)->node1)->Y);
(lines + i)->x2 = (int)((View.Model.Node.Items + (View.Model.Edge.Items + i)->node2)->X);
(lines + i)->y2 = (int)((View.Model.Node.Items + (View.Model.Edge.Items + i)->node2)->Y);
}
}
...
build_lines(View, &lines); // вызов
...
Answer the question
In order to leave comments, you need to log in
You are allocating an array, so in my opinion a pointer to a pointer is needed here:
int allocate_lines(struct line** lines, int Number)
{
lines* = (line*)malloc(Number*sizeof(struct line));
if (!lines)
{
return CANT_ALLOCATE_LINES;
}
return OK;
}
...
struct line * lines;
error = allocate_lines(&lines, View.Model.Edge.Number);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question