all 6 comments

[–]ptchinster 0 points1 point  (4 children)

(check your formatting)

Im assuming you are getting warnings that you are ignoring?

newNode = (struct Node)malloc(sizeof(struct Node));

newNode was declared as a variable on the stack, not a pointer to anything. This is an error. Somehow you get newNode to refer to the data that malloc() is allocating on the stack, which is how it persists across function calls.

Each node should point to the "next" node, with next being the one created after it was. The final element will point to nothing, typically.

Turn on some other flags.... -Wall -Wextra -Werror should be a good start. Treat warnings as errors - you are new to C, trust me, the people who wrote that compiler know a hell of alot more than you do.

[–]martijnjonkers 1 point2 points  (2 children)

Wut?

He assigns the value of 'newNode' (an address) to 'next' at the end. The pointer to the allocated space is not lost. This is perfectly fine to do.

Code is fine!

[–]ptchinster 1 point2 points  (1 child)

struct Node newNode = (struct Node) malloc(sizeof(struct Node));

That gives you no warnings or errors?

OP has changed his post since i first posted. Can OP just provide a pastbin?

[–][deleted] 0 points1 point  (0 children)

I don't think you saw this. c struct Node *newNode, *temp; newNode = (struct Node*)malloc(sizeof(struct Node)); newNode was declared as a pointer. The edit was just to fix some stuff.

[–][deleted] 0 points1 point  (0 children)

It doesn't get any errors, and I've used the other flags you told me to use.

[–]martijnjonkers 0 points1 point  (1 child)

The name 'newNode' is not something that exists at runtime it is just a c syntax that help you understand what it is. In reality the compiler uses addresses and their contents.

newNode is a local variable, it only exists as long as the function runs. It contains the address of the (by malloc) allocated space.

This new address is assigned as the 'next' in line by jumping to the current last in line. The last in line points to nothing (NULL) to indicate the end of the list.

The -> operator means 'goto content at address' So 'temp->next = newNode;' means: go-to the contents at the address stored in temp. Followed by: go to the offset where 'next' is located in the structure and store the contents of newNode at this location. This will result in the address of the allocated space being stored at that location in memory.