N
N
nait1233212016-04-24 14:12:49
C++ / C#
nait123321, 2016-04-24 14:12:49

Where is the error in the code (Dynamic Data Structures)?

Hello, there are problems with the lab.
Here is the task: Given a pointer P3 to the 3rd element of a non-empty list. Duplicate all elements in the list with paired values ​​three times and output the 11th element of the transformed list.
Here is my code:

#include <stdlib.h>
#include <stdio.h>
#define N 10
struct TNode 
{
  int data; //  Інформаційний блок
  struct TNode *next; // Адресний блок
};
typedef struct TNode Node;// Створення власного типу
void CreateNode(Node** head, int d)
{
  Node *tmp = (Node*)malloc(sizeof(Node));// Виділення пам'яті під новий елемент
  tmp->data = d;//Запис інформації у новий елемент
  tmp->next = (*head); //Додавання елемента на початок списку
  (*head) = tmp;// Вказування на голову списку
}

int main()
{
  int t;
  Node *head = NULL; // Покажчик, що вказує на голову списку
  Node *head1 = NULL; // Покажчик, що вказує на голову списку
  Node *p1 = NULL; // Покажчик, що вказує на голову списку
  Node *p3 = NULL; // Покажчик, що вказує на голову списку
  for (int i = N; i >= 0; i--) // Цикл для створення N вузлів
  {
    CreateNode(&head, i);
  }

  head1 = head;
  p3 = head;
  printf("head=%d\n", head);
  printf("head1=%d\n", head1);
  printf("p2=%d\n", p3);
  for (int l = 0; l < 3;l++)
  {
    for (int i = 0; i <= N - 1; i++)
    {
      t = p3;
      if (t % 2 == 0)
      {
        Node *tmp = (Node*)malloc(sizeof(Node));
        p3->next = tmp;
        tmp->data = p3->data;
        tmp->next = NULL;
      }
      p3 = p3->next;
    }
  }
  while (head1) // Виведення результатів
  {
    printf("%d\n", head1->data);
    head1 = head1->next;
  }
  _getch();
  return 1;
}

But when I run it, it looks like this:
Hjr7e8IDx3E.jpg
What's wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Bogachev, 2016-04-24
@sfi0zy

I don't know what compiler you're using to compile this, but gcc quite authoritatively states here
which in a sense corresponds to
which, as it were, hints at the not quite defined behavior of this very t in case it is still compiled somehow.

A
abcd0x00, 2016-04-25
@abcd0x00

/**/
      if (t % 2 == 0)
      {
        Node *tmp = (Node*)malloc(sizeof(Node));
        p3->next = tmp;
        tmp->data = p3->data;
        tmp->next = NULL;
      }

There's a memory leak here. When you do p3->next = tmp, the pointer that was in p3->next.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question