1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
// Declare a "struct type" called "struct Node" for a linked list of ints.
struct Node { // On our platform…
int value; // 4 bytes
struct Node* next; // 8 bytes
}; // entire object: 12 bytes
int main(int argc, char* argv[]) {
// Create a linked list with one int on the HEAP.
// Create one node with value 5
struct Node* head = malloc(sizeof(*head));
// (*head).value = 5; // ugly way
// (*head).next = NULL;
// head -> value = 5; // nicer way
// head -> next = NULL; // nicer way
//
// Best way: Assign to a whole struct object at once.
(*head) = (struct Node) { .value = 5, .next = NULL };
printf("head -> value == %d\n", head -> value);
printf("head -> next == %p\n", (void*)head -> next);
// Add another node
struct Node* new_node = malloc(sizeof(*new_node));
(*new_node) = (struct Node) { .value = 6, .next = NULL };
head -> next = new_node;
free(head);
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2020 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.