I`m learning by myself Clang, and started with pointers. To learn a bit I started creating a simple LinkedList program to try to "play" with pointers and addresses.
#include <stdio.h>
struct Node
{
double value;
struct Node *nextNode;
};
struct LinkedList
{
struct Node *initialNode;
};
int
addFirstElement (struct LinkedList *container, struct Node *newElement)
{
container->initialNode = newElement;
return 1;
}
int
add (struct LinkedList *container, struct Node *newElement)
{
struct Node *iterator = container->initialNode;
int addedCorrectly = 1;
if (iterator == NULL)
addedCorrectly = addFirstElement (container, newElement);
else
{
while (iterator->nextNode != NULL)
iterator = iterator->nextNode;
iterator->nextNode = newElement;
}
return addedCorrectly;
}
/*Esta funcion no genera bien la dirección de memoria, pasa algo raro*/
int
addValue (struct LinkedList *container, double val)
{
struct Node newElement = {val, NULL};
return add (container, &newElement);
}
void
printList (struct LinkedList *container)
{
struct Node *element = container->initialNode;
printf("HEADER => ");
while (element != NULL)
{
printf ("%f -> ", element->value);
element = element->nextNode;
}
printf("NULL\n");
}
int
main ()
{
struct LinkedList container = { NULL };
struct Node val = { 15., NULL };
struct Node val2 = { -19., NULL };
struct Node val3 = {29., NULL};
add(&container, &val);
add(&container, &val2);
add(&container, &val3);
addValue(&container, 29.5);
printList(&container);
}
Everything went smoothly until i wrote the function addValue, which simply creates a Node structure to add it at the end of the LinkedList struct. The problem appears when i create a new element with this function and try to print the list with printList. I had to debug the code and found something really weird. Right when the function is executed, a new NextNode is created (the new address is 0x7fffffffdda8, with a value of 6.9533558074010171e-310 and creates a new pointer to 0x402e000000000000)
¿What really happens here?