0

There is no errors or warnings and there are no problems in the main. this function supposed to get a sorted array and its size and to return a node which contains at the first size/2 indexes (size is the size of the array) numbers from the bigger to the smaller and then up to size/2 should put numbers from the smaller to the bigger. I strongly believe the problem isn't in the concept whereas it is in my understanding of how structures/nodes work.

typedef struct cell *CellPtr;
typedef struct cell{
    int num;
    CellPtr next;
    CellPtr prev;
}Cell;

void fill_node(CellPtr *head, int array[], int size)
{
    CellPtr finally;
    int i;
    if((finally=(CellPtr)malloc(sizeof(Cell)))==NULL)
    {
        printf("Allocation Error\n");
        exit(1);
    }
    for(i=size-1; i>=size/2; i--)
    {
        if((finally->next=(CellPtr)malloc(sizeof(Cell)))==NULL)
        {
            printf("Allocation Error\n");
            exit(1);
        }
        finally->num=array[i];
        finally=finally->next;
    }
    for(i=0; i<size/2; i++)
    {
        if((finally->next=(CellPtr)malloc(sizeof(Cell)))==NULL)
        {
            printf("Allocation Error\n");
            exit(1);
        }
        finally->num=array[i];
        finally=finally->next;
    }
    finally->next=NULL;
    *head=finally;
    return;
}
  • 2
    You already allocated `size` Cells in the first `malloc()`, you don't need to allocate them again in the loops. – Barmar Jun 12 '20 at 16:09
  • 1
    [dont cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Jun 12 '20 at 16:09
  • 1
    `*head = finally;` is setting head to point to the *last* node in the list, not the first. – Barmar Jun 12 '20 at 16:10
  • I edited the thing about malloc and still not working. – Ahmad Istaitih Jun 12 '20 at 16:12
  • How could Ihave the first of the node – Ahmad Istaitih Jun 12 '20 at 16:12
  • 2
    One way would be to build your list in the reverse order, adding nodes to the front instead of the end. Then at the end, the current node will be the first node. – Barmar Jun 12 '20 at 16:14
  • the posted code does not compile! first because it is missing the needed `#include` statements for the header files: `stdio.h` and `stdlib.h` – user3629249 Jun 12 '20 at 17:40
  • OT: regarding: `printf("Allocation Error\n");` Error messages should be output to `stderr`, not `stdout`. When the error indication is from a C library function, then should also output to `stderr` the text reason the system thinks the error occurred. The function: `perror( "Allocation Error" ); handles both of these outputs – user3629249 Jun 12 '20 at 17:45

1 Answers1

0

regarding:

finally->next=NULL;
*head=finally;

This results in head pointing to a single node rather than to a linked list of nodes

user3629249
  • 16,402
  • 1
  • 16
  • 17