relocate
C comes with a very useful function called
reallocthat will reallocate the memory for you.realloctakes two arguments. First, it asks you to specify the array you are attempting to copy. Second, it asks you to specify the size to which you would like the final array to be. Modify your code as follows:// Implements a list of numbers with an array of dynamic size using realloc #include <stdio.h> #include <stdlib.h> int main(void) { // List of size 3 int *list = malloc(3 * sizeof(int)); if (list == NULL) { return 1; } // Initialize list of size 3 with numbers list[0] = 1; list[1] = 2; list[2] = 3; // Resize list to be of size 4 int *tmp = realloc(list, 4 * sizeof(int)); if (tmp == NULL) { free(list); return 1; } list = tmp; // Add number to list list[3] = 4; // Print list for (int i = 0; i < 4; i++) { printf("%i\n", list[i]); } // Free list free(list); return 0; }Notice that
int *tmp = realloc(list, 4 * sizeof(int))creates a list of size four integers. Then, it copies the values oflistto this new array. Finally, a pointer calledtmppoints to the location of memory of this new array. The copying is handled byrealloc. Once that copy is made, the memory at the location oflistis freed. Then, the pointer calledlistis pointed at the location oftmp, where the new array is located.You can imagine how using
reallocfor a queue or stack could be useful. As the amount of data grows,realloccould be used to grow or shrink the stack or queue.
http, css and url
response codes
200 OK
301 Moved Permanently
302 Found
304 Not Modified
304 Temporary Redirect
401 Unauthorized
403 Forbidden
404 Not Found
418 I'm a Teapot
500 Internal Server Error
503 Service Unavailable
