295 words
1 minutes
CS50
2024-04-19

relocate#

  • C comes with a very useful function called realloc that will reallocate the memory for you. realloc takes 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 of list to this new array. Finally, a pointer called tmp points to the location of memory of this new array. The copying is handled by realloc. Once that copy is made, the memory at the location of list is freed. Then, the pointer called list is pointed at the location of tmp, where the new array is located.

  • You can imagine how using realloc for a queue or stack could be useful. As the amount of data grows, realloc could 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
CS50
https://tubehao.github.io/blog/posts/learn/cs50/
Author
tubehao
Published at
2024-04-19