#include <stdio.h>
#include <stdlib.h>
// Node structure for linked list
typedef struct Node {
int data;
struct Node* next;
} Node;
// Function to create a new node
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to print array
void printArray(int arr[], int size) {
printf("Array: ");
for (int i = 0; i < size; i++) {
printf("[%d]", arr[i]);
}
printf("\n");
}
// Function to print linked list
void printList(Node* head) {
printf("Linked List: ");
Node* curr = head;
while (curr != NULL) {
printf("%d -> ", curr->data);
curr = curr->next; // advance curr to next node
}
printf("null\n");
}
int main() {
// Array with 3 elements
int arr[3] = {1, 2, 3};
// Linked list with 3 nodes
Node* head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
printArray(arr, 3);
printList(head);
// Print memory addresses for array elements
printf("Array element addresses:\n");
for (int i = 0; i < 3; i++) {
printf("Element %d at address %p\n", arr[i], (void*)&arr[i]);
}
// Print memory addresses for linked list nodes
printf("Linked list node addresses:\n");
Node* curr = head;
while (curr != NULL) {
printf("Node with data %d at address %p, next points to %p\n", curr->data, (void*)curr, (void*)curr->next);
curr = curr->next; // advance curr to next node
}
return 0;
}
curr = curr->next; // advance curr to next node
advance curr pointer to traverse linked list nodes
for (int i = 0; i < size; i++) { printf("[%d]", arr[i]); }
iterate array elements to print them
printf("Element %d at address %p\n", arr[i], (void*)&arr[i]);
show contiguous memory addresses of array elements
printf("Node with data %d at address %p, next points to %p\n", curr->data, (void*)curr, (void*)curr->next);
show scattered memory addresses and next pointers of linked list nodes
Array: [1][2][3]
Linked List: 1 -> 2 -> 3 -> null
Array element addresses:
Element 1 at address 0x7ffee3b7a9a0
Element 2 at address 0x7ffee3b7a9a4
Element 3 at address 0x7ffee3b7a9a8
Linked list node addresses:
Node with data 1 at address 0x600003f80010, next points to 0x600003f80030
Node with data 2 at address 0x600003f80030, next points to 0x600003f80050
Node with data 3 at address 0x600003f80050, next points to (nil)