Adding new item to list c
In C, you can add a new item to a list (which is typically implemented as an array) by using the following methods:
- Dynamic Memory Allocation: You can use the
malloc
function to allocate a new block of memory, and then assign the new item to that memory location. Here's an example:#include <stdlib.h>
int main() { int list = malloc(sizeof(int) 5); // allocate memory for 5 integers list[0] = 1; list[1] = 2; list[2] = 3; list[3] = 4; list[4] = 5;
// add a new item to the list
int* new_item = malloc(sizeof(int));
*new_item = 6;
list = realloc(list, sizeof(int) * 6); // reallocate memory to accommodate the new item
list[5] = *new_item;
free(new_item); // free the memory allocated for the new item
// print the updated list
for (int i = 0; i < 6; i++) {
printf("%d ", list[i]);
}
printf("\n");
free(list); // free the memory allocated for the list
return 0;
}
2. **Using a Linked List**: You can use a linked list data structure, where each node contains a value and a pointer to the next node. You can add a new item to the list by creating a new node and linking it to the existing nodes. Here's an example:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node* next;
} Node;
Node* create_node(int value) {
Node* node = malloc(sizeof(Node));
node->value = value;
node->next = NULL;
return node;
}
void add_item(Node** head, int value) {
Node* new_node = create_node(value);
if (*head == NULL) {
*head = new_node;
} else {
Node* current = *head;
while (current->next!= NULL) {
current = current->next;
}
current->next = new_node;
}
}
void print_list(Node* head) {
while (head!= NULL) {
printf("%d ", head->value);
head = head->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
// add items to the list
add_item(&head, 1);
add_item(&head, 2);
add_item(&head, 3);
add_item(&head, 4);
add_item(&head, 5);
add_item(&head, 6);
// print the updated list
print_list(head);
return 0;
}
Note that in the linked list example, we use a pointer to a pointer (Node** head
) to represent the head of the list, and we use the add_item
function to add new items to the list.