D
D
Dmitry2016-03-20 20:39:59
C++ / C#
Dmitry, 2016-03-20 20:39:59

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;
  // остальные поля
};

Under Items in the edge and node structures, allocated dynamically:
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;
  }
}

Next, I initialize another view structure:
struct line
{
  int x1, x2, y1, y2;
};

I do it like this:
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);

Further, after calling this function (namely, after its completion, and not during the loop), everything that was in the View structure is deleted (it seems to be shifted):
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); // вызов
...

Why is this happening? Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Beloshitsky, 2016-03-20
@HaseProgram

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);

R
res2001, 2016-03-20
@res2001

The debugger should help you in your trouble.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question