I have looked at many different questions online and cannot figure out what I am doing wrong. I may be headed in the wrong direction now because I have tried so many different t
For starters even the first statement of the function is wrong because the value of the parameter first
is overwritten.
Node* addFront(Node* first, double x, double y) {
first = malloc(sizeof(Node));
//...
The function can look the following way
Node * addFront( Node *first, double x, double y )
{
Node *temp = malloc( sizeof( Node ) );
if ( temp != NULL )
{
temp->x = x;
temp->y = y;
temp->next = first;
first = temp;
}
return first;
}
Or with a testing code
Node * addFront( Node *first, double x, double y )
{
Node *temp = malloc( sizeof( Node ) );
if ( temp != NULL )
{
temp->x = x;
temp->y = y;
temp->next = first;
first = temp;
}
// start pf inline test
size_t size = 0;
for ( Node *current = first; current != NULL; current = current->next )
{
printf( "(%.4f, %.4f)\n", current->x, current->y );
++size;
}
printf( "Size: %zu\n", size );
// end pf inline test
return first;
}
This block doesn't make sense at all:
first = malloc(sizeof(Node));
if (first == NULL) {
first->x = x;
first->y = y;
first->next = NULL;
}
Probably you wanted to move the first = malloc(sizeof(Node));
inside the block. It would work, however it's completely unnecessary because it would be logically equal to the else
block. So you can leave just the second block there:
Node * temp = malloc(sizeof(Node));
temp->x = x;
temp->y = y;
temp->next = first;
first = temp;
return first;
// or rather return temp directly
There is one more point - you should add error handling in case malloc
runs out of memory, so you should check for temp == NULL
and act accordingly (return NULL
from function or whatever...).