I am new to C and I want to implement the linked list. This is my initial copied code:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data; // integer data
struct Node* next; // pointer to the next node
} Node;
int main() {
Node* A = NULL;
Node* temp = malloc(sizeof * temp);
temp->data = 2;
temp->next = NULL;
A = temp;
printf("%d", A);
return 0;
}
I have understood how pointers work, for example:
//Example 2
int a = 2;
int* p = &a;
such that p holds the address of a and *p holds the content of it.
In the node example, the basic idea is to create an initial node, and then from there, to link other nodes when inserting at the end for instance. So, when we did this:
Node* A = NULL;
Node* temp = malloc(sizeof * temp);
we create a node A, my first question here, why I can't use the same concept of accessing its address and content NULL the same as in Example 2 or how can I do that?
Second, when we created node temp and assigned 2 to its data, and NULL to its next, it's all clear, but when we did A = temp, this is not clear, what did we assigned exactly? I mean, how can I get from A to the next node, A now has A->data = 2 and A->next = NULL, I was expecting A->next to store the address of temp, no? Please if you can explain in the simplest terms the basic abstract inner workings?
Update
For example, if I want to create a linked list with two elements 2 and 3. Is the following code correct?
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data; // integer data
struct Node* next; // pointer to the next node
} Node;
int main() {
Node* A = NULL;
Node* temp = malloc(sizeof * temp);
temp->data = 2;
temp->next = NULL;
A->next = temp;
Node* temp1 = malloc(sizeof * temp1);
temp1->data = 3;
temp1->next = NULL;
temp->next = temp1;
return 0;
}
temp, not 2 nodes. because you madeAa pointer to a struct, not a struct. Also, be careful about assigning local (stack) variables to pointers. (int* p = &a;) If you do that in a function instead of in main, the memory allocation disappears when you return from the function and the pointer to it becomes invalid.printf("%d", A);is wrong. Maybe you wantedprintf("%d", A->d);or perhapsprintf("%p", (void*)A);