Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- /* ... */
- // we now want our addToList function to return something to handle errors
- int addToList(struct list *myList, int item);
- /* ... */
- // Inside the main function
- // Add any number of items to the list specified by the amount variable
- amount = 44;
- for (int i = 0; i < amount; i++) {
- if ( addToList(&myList, i + 1) ) {
- free(myList.data);
- myList.data = NULL;
- return -1;
- }
- }
- /* ... */
- // This function adds an item to a list
- // if an error occured the functions returns 1, else 0
- int addToList(struct list *myList, int item) {
- // If the list is full then resize the memory to fit 10 more items
- if (myList->numItems == myList->size) {
- myList->size += 10;
- int *temp = NULL;
- temp = realloc( myList->data, myList->size * sizeof(int) );
- if (NULL == temp) {
- perror("Failed to reallocate memory, the program should stop");
- return -1;
- }
- myList->data = temp;
- temp = NULL;
- }
- /* ... */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement