#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node* next; } Node; int main() { int arr[3] = {10, 20, 30}; printf("Array addresses:\n"); for (int i = 0; i < 3; i++) { printf("%p ", (void*)&arr[i]); } printf("\nLinked list addresses:\n"); Node* head = malloc(sizeof(Node)); head->data = 10; head->next = malloc(sizeof(Node)); head->next->data = 20; head->next->next = malloc(sizeof(Node)); head->next->next->data = 30; head->next->next->next = NULL; Node* current = head; while (current != NULL) { printf("%p ", (void*)current); current = current->next; } printf("\n"); return 0; }
Arrays store elements in contiguous memory locations, so their addresses increase sequentially. Linked list nodes are allocated separately on the heap, so their addresses are scattered.
Each linked list node stores an integer and a pointer to the next node, increasing memory usage. Arrays store only the data elements contiguously without extra pointers.
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* head = malloc(sizeof(Node));
head->data = 1;
// head->next is not set
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
Since head->next is not initialized, it contains garbage. When current moves to current->next, it accesses invalid memory causing a segmentation fault.
#include <stdio.h> #include <stdlib.h> int main() { int arr[4] = {20, 30, 40, 0}; // Insert 10 at beginning of array by shifting for (int i = 3; i > 0; i--) { arr[i] = arr[i-1]; } arr[0] = 10; printf("Array after insertion: "); for (int i = 0; i < 4; i++) { printf("%d ", arr[i]); } printf("\n"); typedef struct Node { int data; struct Node* next; } Node; Node* head = malloc(sizeof(Node)); head->data = 20; head->next = malloc(sizeof(Node)); head->next->data = 30; head->next->next = malloc(sizeof(Node)); head->next->next->data = 40; head->next->next->next = NULL; // Insert 10 at beginning of linked list Node* new_node = malloc(sizeof(Node)); new_node->data = 10; new_node->next = head; head = new_node; printf("Linked list after insertion: "); Node* current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); return 0; }
In the array, elements are shifted right to make space at index 0. In the linked list, a new node is created and set as head pointing to old head.
Arrays have contiguous memory, so the address of any element can be computed quickly. Linked lists store nodes scattered in memory, so to reach the 5th element, you must follow 4 pointers sequentially.
